简体   繁体   中英

Communication between specific web page and chrome extension

I try to create a communication channel between specific webpage (per example : www.website.dev) and a chrome extension I created.

By using postMessage it's work from webpage to extension but I can't do that from extension to webpage.

I tried Google example but it uses background page

Thanks for your help

EDIT : sorry I don't understand the difference between content_script and background.js In my manifest I have content script = test.js What's about "background" ?

Following the documentation you can pass messages to your extension if you know the extension id: https://developer.chrome.com/extensions/messaging#external-webpage

manifest.json

"externally_connectable": {
  "matches": ["*://*.example.com/*"]
}

website:

// The ID of the extension we want to talk to.
var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";

// Make a simple request:
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
  function(response) {
    if (!response.success)
      handleError(url);
  });

extension:

chrome.runtime.onMessageExternal.addListener(
  function(request, sender, sendResponse) {
    if (sender.url == blocklistedWebsite)
      return;  // don't allow this web page access
    if (request.openUrlInEditor)
      openUrl(request.openUrlInEditor);
  });

You will find all the details in the documentation https://developer.chrome.com/extensions/messaging

You would have one piece use sendMessage function while the other piece is listening for the event, which could be either a webpage or content script.

either the webpage's content script should initiate the communication (so you would get the tab id) or you can have the background query for tabs with specific url and then use sendMessage. Notice two separate functions chrome.extension.sendMessage and chrome.tabs.sendMessage used here.

the following code works for me:

content_script.js:

chrome.extension.sendMessage({"msg":"hello"});

background.js:

chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.msg == "hello"){
    senderTab = sender.tab.id;
    chrome.tabs.sendMessage(senderTab, {"msg": "ehlo"});
  };
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM