Extension can't access to custom functions in window object

google-chrome, google-chrome-extension, javascript

Solution

This is for security. Content scripts (which `background.js` is executing) are isolated from the tab's scripts (where `customfunc` is defined). You also get the added benefit of not having to worry about namespace clashing (which is where things are messing up for you).

One approach would be to create myscript.js which says `console.log(window)` and then use a content script (or `chrome.tabs.executeScript`) to write `<script src='chrome.extension.getURL("myscript.js")'></script>` to the tab's DOM. You'll also need to add `"web_accessible_resources": ["myscript.js"]` to your manifest.

But with things this complicated, a good question would be why you're needing to access `customfunc`. (You can also take a look at https://stackoverflow.com/a/9517879/2336725 for a longer answer.)

Problem

When a Chrome extension tries to get custom functions in window object via chrome.executeScript, it gets nothing. For example: Tab ID: 150 Tab js: ``` window.customfunc = function(){return 'yeap';} ``` Extension's background JS: ``` chrome.tabs.executeScript(150, { code: "console.log(window);" }) ``` Manifest.json: ``` { "background": { "scripts": [ "background.js" ] }, "content_scripts": [ { "exclude_globs": [ ], "exclude_matches": [ ], "include_globs": [ "*://*/*" ], "js": [ "script.js" ], "matches": [ "http://*/*" ], "run_at": "document_idle" } ], "content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'", "description": "Test", "manifest_version": 2, "name": "Workspace", "permissions": [ "unlimitedStorage", "notifications", "clipboardWrite", "notifications", "clipboardRead", "management", "tabs", "history", "cookies", "idle", "storage", "webRequest", "webRequestBlocking", "contentSettings", "*://*/*" ], "version": "1.0" } ``` Result: In console, the `window` object doesn't show `customfunc`, so we can't use `window.customfunc` with `chrome.executeScript`. Why does this happen, and how can we fix it? Thanks.

Original source

Related problems