Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: executeScript on tab

I've recently started developing my first Google Chrome Extension, and am experiencing an issue that I'm not entirely sure how to fix.

In my script, I'm checking if a tab is open to a specific website, and, if so, I'm performing the following code:

chrome.tabs.update(tab.id, {active: true});

// Execute code on the existing tab to open the Message.
chrome.tabs.executeScript(tab.id, {
    "code": "messageOpen(15, false);"
});

The above code should update the tab setting it as active and should then attempt to execute a function called messageOpen(). The problem I'm experiencing is that the function messageOpen() exists as a function that was included in the <HEAD> of my website, but not my extension.

Hence, when attempting to execute the messageOpen() function, I'm receiving this error:

Uncaught ReferenceError: messageOpen is not defined

I'm 100% positive that the messageOpen() function works if I browse the website regularly, but when using executeScript, it's as if the extension is incapable of running functions that have already been loaded in my active tab.

Does anybody have some suggestions or alternatives?

like image 834
user1298740 Avatar asked Feb 12 '23 18:02

user1298740


1 Answers

This happens because content scripts cannot interact with the window object of the page they are injected to. If you want to execute a script that uses your messageOpen() function then you'll have to inject that code into the page context using a <script>, like this:

var myScript = document.createElement('script');
myScript.textContent = 'messageOpen(15, false);';
document.head.appendChild(myScript);

So, if you want to inject this code using the executeScript() method and the "code" property you can do it like this:

chrome.tabs.update(tab.id, {active: true});

// Execute code on the existing tab to open the Message.
chrome.tabs.executeScript(tab.id, {
    "code": "var myScript = document.createElement('script');"
        + "myScript.textContent = 'messageOpen(15, false);';"
        + "document.head.appendChild(myScript);"
});

NOTE: since January 2021, use Manifest V3 with chrome.scripting.executeScript() instead of chrome.tabs.executeScript().

like image 109
Marco Bonelli Avatar answered Feb 15 '23 02:02

Marco Bonelli