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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With