atom
atom

Reputation: 167

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

Upvotes: 3

Views: 3552

Answers (2)

Xan
Xan

Reputation: 77571

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.

Upvotes: 13

Moin
Moin

Reputation: 1143

Use chrome.runtime.id like this:

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

Upvotes: 1

Related Questions