Home > Enterprise >  Chrome Extension - How to interact between the main extension popup (default_popup) and a page scrip
Chrome Extension - How to interact between the main extension popup (default_popup) and a page scrip

Time:11-06

I created an extension, where I placed a script into a page markup and performs some actions according to the following enter image description here

manifest.json

{
  "name": "content_scripts   popup",
  "version": "1.0",
  "manifest_version": 3,
  "content_scripts": [
    {
      "js": [
        "matches.js"
      ],
      "matches": [
        "<all_urls>"
      ]
    }
  ],
  "host_permissions": [
    "<all_urls>"
  ],
  "action": {
    "default_popup": "popup.html"
  }
}

popup.js

chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
  console.log("Send");
  chrome.tabs.sendMessage(tabs[0].id, "message", (response) => {
    console.log("Recv response = "   response.title);
    document.getElementById("title").innerText = response.title;
  });
});

matches.js

console.log("matches.js");

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log("Recv. Send response = "   document.title);
  sendResponse({ title: document.title });

  return true;
});

popup.html

<!DOCTYPE html>
<html>

<head>
  <style type="text/css">
    * {
      font-size: x-large;
    }
  </style>
</head>

<body style="min-width:300px">
  <div id="title"></div><br>
  <script src="popup.js"></script>
</body>

</html>
  • Related