Injected scripts

715 views
Skip to first unread message

Mark Dostie

unread,
Apr 8, 2022, 2:42:27 PM4/8/22
to Chromium Extensions
I use the scripting API quite extensively in my new v3 extension (migrating from a v2) and there seems to be some odd things.

I have a script border.js which gets injected into a tab by the service worker:

chrome.scripting.executeScript( {
                            target: {tabId: tabId},
                            files: ["border.js"],
                            world: chrome.scripting.ExecutionWorld.MAIN,
                        }, function (e) {
                            console.log("Added border.js");                          
                        });



And at one point border.js calls:

chrome.runtime.sendMessage(extensionid, {action: 'openlink', payload: $(this).prop('href')}, function(response) {
            console.log('Openlink message sent');         
        });

To send a message back to the service worker...

The console complains that I need to send the id of the extension. But when I call chrome.runtime.id it is undefined so I need to hard code the extension id.

When I do that (hard-code) the message never arrives at the service worker (background.js) even though I see the "openlink message sent" in the console for the page.

I assume I'm missing something that has changed between v2 and v3 any suggestions?

Thanks,
Mark

Stefan vd

unread,
Apr 9, 2022, 10:53:47 AM4/9/22
to Chromium Extensions, dostie%t...@gtempaccount.com
Hi there,

The "extensionId" is an optional string. If you want to send it to another Chrome extension.
Can you try it without the "extensionId" in your code:
chrome.runtime.sendMessage({action: 'openlink', payload: $(this).prop('href')}, function(response) {

     console.log('Openlink message sent');        
 });


Thanks,
Stefan vd

wOxxOm

unread,
Apr 9, 2022, 10:58:18 AM4/9/22
to Chromium Extensions, dostie%t...@gtempaccount.com
  1. When you inject the code into the MAIN world, it is a normal page script, not a content script, i.e. not a part of the extension anymore, so it can't access `chrome.runtime.id`.

  2. In order to send messages from a page via chrome.runtime.sendMessage you need to use "external messaging", but it doesn't support <all_urls>, so if you need that, instead of sendMessage you'll send a CustomEvent DOM event to a normal content script, which will then relay the event's `detail` to the background script via chrome.runtime.sendMessage. There should be googlable examples of doing that. In the future chrome.scripting will allow such MAIN world script to communicate with the content script directly.
Reply all
Reply to author
Forward
0 new messages