Open my chrome extension by clicking on my webpage's button

131 Views Asked by At

I am trying to develop a chrome extension where I want to open my chrome extension by clicking on my webpage's button. Is there any possibilities to do so?

i.e. when I click a button on webpage the popup file of extension should show .

I have created manifest.json, popup html, content.js and background js as well and here are the code for each respectively:

manifest.json

{
  "name": "Popup extension",
  "version": "1.0",
  "description": "popup popup",
  "manifest_version": 3,
  "action": {
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "content.js"
      ]
    }
  ],
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "cookies",
    "tabs",
    "activeTab",
    "scripting",
    "storage"
  ],
  "host_permissions": [
    "https://www.google.com/*"
  ]
}

popup.html

<!DOCTYPE html>
<html>
<head>
  <title>pop chrome extension</title>
</head>
<body>
  <h1>Hi Popup here</h1>
  <p id="demo"></p>

  <script src="popup.js">
    
  </script>
</body>
</html>

content.js

document.querySelector(".btn").addEventListener("click", function () {
  
  chrome.runtime.sendMessage({ action: 'openPopup' });
});

background.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  if (message.action === 'openPopup') {
    // Open the extension's popup
    chrome.browserAction.openPopup();
  }
});

Here is my webpage html file:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get login status</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <button class="btn" >open popup</button>
    </div>

    <script src="index.js"></script>
</body>
</html>

After running the code i get following error:

Uncaught Error: Extension context invalidated.
    at HTMLButtonElement.<anonymous>

Whis is possible wrong in this code or what can i do to improve it?

0

There are 0 best solutions below