executeScript function can't access full window/globalThis object

1,621 views
Skip to first unread message

Marc Lajoie

unread,
Mar 21, 2023, 1:17:02 PM3/21/23
to Chromium Extensions
Hi, I'm struggling with a devilish issue.

So, I run a function from my popup using `chrome.scripting.executeScript`, invoking it like this:

```
await chrome.scripting.executeScript({
    target: { tabId, allFrames: true },
    func: inPageFunction,
});
```

So far so good. inPageFunction can interact with the current tab, and everything seems to work, so I know my permissions are correct.

Here's where the problem lies:
If inPageFunction tries to access a global variable that is set by site on the window/globalThis object, it comes back undefined.

```
function inPageFunction() {
   console.log(window.theGlobal); // gives undefined
}
```

However, if I open the console on that site, and run `console.log(window.theGlobal)`, I get a result.

The executeScript is invoked by a button in the popup. I'll hit the button, check the console, and see it has outputted "undefined". I'll then immediately run `console.log(window.theGlobal)` and see theGlobal is indeed defined.

Does my content script not have access to the full window/globalThis object? Is it filtered in some way? I can't figure this out. Any help would be appreciated.

(Manifest v3, btw)

Marc


Oliver Dunk

unread,
Mar 21, 2023, 1:55:42 PM3/21/23
to Marc Lajoie, Chromium Extensions
Hi Marc,

Extensions have the concept of "isolated worlds". These are separate JavaScript contexts which can access the same DOM. We have some documentation on those here: https://developer.chrome.com/docs/extensions/mv3/content_scripts/#isolated_world

By default, scripting.executeScript executes in the isolated world. But you can specify a world explicitly to override this: https://developer.chrome.com/docs/extensions/reference/scripting/#property-ScriptInjection-world

Hopefully that helps!
Oliver Dunk | DevRel, Chrome Extensions | https://developer.chrome.com/ | London, GB


--
You received this message because you are subscribed to the Google Groups "Chromium Extensions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extens...@chromium.org.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-extensions/77ef517f-61cb-4966-8f40-d90afcf7dfcbn%40chromium.org.

Marc Lajoie

unread,
Mar 21, 2023, 2:25:09 PM3/21/23
to Chromium Extensions, Oliver Dunk, Chromium Extensions, Marc Lajoie
Thanks, you're a champion. That completely solved it. I don't think I would have ever found that in the docs on my own.

Marc

Oliver Dunk

unread,
Mar 21, 2023, 2:33:54 PM3/21/23
to Marc Lajoie, Chromium Extensions
No problem! I'll make a mental note that we might want to improve the docs here.
Oliver Dunk | DevRel, Chrome Extensions | https://developer.chrome.com/ | London, GB

Reply all
Reply to author
Forward
0 new messages