chrome.tabs.executeScript: How to get access to variable from content script in background script?
google-chrome-extension, javascript
Solution
To avoid above error use following code
if (tab.url.indexOf("chrome-devtools://") == -1) {
chrome.tabs.executeScript(tabId, {
file: "app.js"
}, function () {
if (app.getSettings('authorizeInProgress')) {
alert('my tab');
REDIRECT_URI = app.getSettings('REDIRECT_URI');
if (tab.url.indexOf(REDIRECT_URI + "#access_token") >= 0) {
app.setSettings('authorize_in_progress', false);
chrome.tabs.remove(tabId);
return app.finishAuthorize(tab.url);
}
} else {
alert('not my');
}
});
}
instead of
chrome.tabs.executeScript(null, {
file: "app.js"
}, function () {
if (app.getSettings('authorizeInProgress')) {
alert('my tab');
REDIRECT_URI = app.getSettings('REDIRECT_URI');
if (tab.url.indexOf(REDIRECT_URI + "#access_token") >= 0) {
app.setSettings('authorize_in_progress', false);
chrome.tabs.remove(tabId);
return app.finishAuthorize(tab.url);
}
} else {
alert('not my');
}
});
Explanation
- `chrome://extensions/` page also fires `chrome.tabs.onUpdated` event, to avoid it we have to add a filter to skip all dev-tool pages.
Problem
How to get access to variable `app` from content script `app.js` in background script `background.js`? Here is how I try it (`background.js`): ``` chrome.tabs.executeScript(null, { file: "app.js" }, function() { app.getSettings('authorizeInProgress'); //... }); ``` Here is what I get: Here is `manifest.json`: ``` { "name": "ctrl-vk", "version": "0.1.3", "manifest_version": 2, "description": "Chrome extension for ctrl+v insertion of images to vk.com", "content_scripts": [{ "matches": [ "http://*/*", "https://*/*" ], "js": ["jquery-1.9.1.min.js" ], "run_at": "document_end" }], "web_accessible_resources": [ "jquery-1.9.1.min.js" ], "permissions" : [ "tabs", "http://*/*", "https://*/*" ], "background": { "persistent": false, "scripts": ["background.js"] } } ``` Full code for instance, at github https://github.com/MaxLord/ctrl-vk/tree/with_bug