Javascript chrome.tabs.executeScript:如何从后台脚本中的内容脚本访问变量?
如何从后台脚本Javascript chrome.tabs.executeScript:如何从后台脚本中的内容脚本访问变量?,javascript,google-chrome-extension,Javascript,Google Chrome Extension,如何从后台脚本background.js中的内容脚本app.js访问变量app 下面是我如何尝试的(background.js): 以下是我得到的: 下面是manifest.json: { "name": "ctrl-vk", "version": "0.1.3", "manifest_version": 2, "description": "Chrome extension for ctrl+v insertion of images to vk.com", "cont
background.js
中的内容脚本app.js
访问变量app
下面是我如何尝试的(background.js
):
以下是我得到的:
下面是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"]
}
}
完整代码,例如,在github
为避免上述错误,请使用以下代码
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');
}
});
}
而不是
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');
}
});
解释
页面也会触发chrome://extensions/
事件,为了避免它,我们必须添加一个过滤器来跳过所有开发工具页面chrome.tabs.onUpdate
"content_scripts": [{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["jquery-1.9.1.min.js"
],
在“匹配”部分中,只有http、https是匹配的,因此如果您在页面中加载扩展,如:'chrome://extensions/'或'file:///D:xxx,则会发生该错误
您可以使用url“http://”在页面中加载扩展名;或者在“匹配项”数组中添加更多规则。(本应将此作为注释提交给已接受的答案,但仍缺乏所需的声誉)
您还应该将tabId作为chrome.tabs.executeScript的第一个参数。否则,在请求URL和background.js对错误页面执行executeScript操作后,用户可能会立即切换窗口/选项卡
虽然事后看来很明显,但当我收到同样的错误消息“无法访问url的内容”时,这让我陷入了困境-devtools://..“即使我的chrome.tabs.onUpdate eventhandler在执行executeScript调用之前正在检查用户请求的页面是否具有特定的域名
所以请记住,chrome.tabs.executeScript(null,…)在活动窗口中运行脚本,即使活动窗口可能是开发人员工具检查器。我想,当我们将第一个参数作为null传递给executeScript()时会发生什么-这意味着我们试图在当前选项卡中执行脚本。这显然不是我们想要的..我们当前需要一种方法来获取这个该死的选项卡的id..您必须使用消息传递或从
executeScript()返回数组值
函数解析内容脚本的值。tab
变量在哪里?我得到Uncaught引用错误:tab未定义
我在onUpdated
事件中找到tab
。谢谢:)
"content_scripts": [{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["jquery-1.9.1.min.js"
],