Some of the other answers here contain useful debugging tips or small puzzle pieces, however, if you want to embed in (third-party) web pages like me, then there are no answers listing the correct components.
There are 4 steps:
- External background listener
- The sender of the foreground message
- insert extension id for message sender
- and the rule in the manifest is to tie everything together.
The example below should be all you need to let you embed js that sends messages from any page on google.com to your own extension
First, in manifest.json, you need to add the messaging rules that are described here :
"externally_connectable": { "matches": ["*://*.google.com/*"] }
Then in the background script or on the page you need an external listener ( not the usual chrome.runtime.onMessage.addListener mentioned in msot answers), this is described here :
chrome.runtime.onMessageExternal.addListener( (request, sender, sendResponse) => { console.log("Received message from " + sender + ": ", request); sendResponse({ received: true });
When you have these parts, you can use the sender of the message , as usual, but with the extension identifier as the first parameter:
chrome.runtime.sendMessage(myExtId, { }, response => { } );
If you do not know how to get the external identifier, which I used as the first parameter, you can insert your extension identifier , as shown below. This is necessary because chrome.runtime.id and @@ extension_id both do not work in embedded scripts:
//create a script tag to inject, then set a variable with the id in that script let idScript = document.createElement("script"); idScript.setAttribute("type", "application/javascript"); idScript.textContent = 'var myExtId = "' + chrome.runtime.id +'";'; let parent = ( document.head || document.documentElement ); parent.insertBefore( idScript, parent.firstChild ); //inject and run your other script here idScript.remove(); //then cleanup
Since we set it to var, another script can now directly access the value