How to dynamically send chrome extension ID to a webpage for message passing

Ad

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) {});
Ad

Answer

Ad

First off, if you already have a content script, you don't have to use externally_connectable to communicate - you could use custom events to communicate 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.

Ad
source: stackoverflow.com
Ad