Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) {});
like image 230
atom Avatar asked Nov 25 '25 16:11

atom


1 Answers

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.

like image 76
Xan Avatar answered Nov 27 '25 04:11

Xan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!