admin管理员组

文章数量:1277303

Im injecting a script in webpage via content script. Inside the script I am using chrome.runtime.sendMessage to successfully send a message to background script. However I have the extensionId hardcoded. How would I dynamically inject the extension id in webpage to send messages to background script?

chrome.runtime.sendMessage(extensionIdHardCoded, {
      msg: data
    },
    function(response) {});

Im injecting a script in webpage via content script. Inside the script I am using chrome.runtime.sendMessage to successfully send a message to background script. However I have the extensionId hardcoded. How would I dynamically inject the extension id in webpage to send messages to background script?

chrome.runtime.sendMessage(extensionIdHardCoded, {
      msg: data
    },
    function(response) {});
Share Improve this question asked Dec 22, 2015 at 2:18 atomatom 1673 silver badges10 bronze badges 2
  • 1 Unfortunately, it must be hardcoded. – Daniel Herr Commented Dec 22, 2015 at 3:00
  • @DanielHerr are there any security measures I should in this scenario? My extension just manipulated JS on the front end, and has callbacks between the webpage and background script. – atom Commented Dec 22, 2015 at 4:26
Add a ment  | 

2 Answers 2

Reset to default 13

First off, if you already have a content script, you don't have to use externally_connectable to municate - you could use custom events to municate with the content script that would forward it to background.


That said, you can use chrome.runtime.id and pass it to the window context before injecting your script:

var script = document.createElement('script');
script.textContent = "var extensionId = " + JSON.stringify(chrome.runtime.id);
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);

/* now inject your script */

Alternatively, you could add an invisible DOM node that would contain the ID as content or some attribute and read that from the injected script.

Use chrome.runtime.id like this:

chrome.runtime.sendMessage(chrome.runtime.id, {
    msg: data
},
function(response) {});

本文标签: javascriptHow to dynamically send chrome extension ID to a webpage for message passingStack Overflow