8

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?

0

2 Answers 2

12

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().

Sign up to request clarification or add additional context in comments.

Comments

2

Here's the working sample to execute js on a tab for Manifest v3:

 chrome.scripting.executeScript({ target: { tabId: tab.id }, func: () => { // write your code here document.body.style.backgroundColor = "red"; }, }); 

You also need to add scripting permission to Manifest.json

 permissions: [ 'scripting', // to execute js into a tab ], 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.