所以我有一个我正在编写的扩展程序,当用户单击pageAction图标时,我正在尝试执行脚本。单击该图标时,该方法将调用chrome.tabs.executeScript(...)。问题是chrome.tabs.executeScript函数没有执行,我不明白为什么。我知道我到了调用executeScript的代码,因为我看到了一个警报。以下是我的一些代码:
的manifest.json
{
"manifest_version": 2,
"name": "name here",
"description": "description here",
"version": "0.1",
"permissions": [
"<all_urls>",
"tabs"
],
"icons": {
"16" : "images/icon16.png",
"48" : "images/icon48.png",
"128": "images/icon128.png"
},
"background": {
"scripts": ["js/check.js"]
},
"page_action": {
"default_icon": {
"19": "images/icon19.png",
"38": "images/icon38.png"
},
"default_title": "default title here"
}
}
JS / check.js
chrome.tabs.onUpdated.addListener(checkForValidUrl);
function checkForValidUrl(tabId, changeInfo, tab) {
if (tab.url.indexOf('g') > -1) {
chrome.pageAction.show(tabId);
}
};
chrome.pageAction.onClicked.addListener(function(tab) {
alert("hello world"); //this code is executed...
//...this code is not
chrome.tabs.executeScript(tab.id, {file: "save.js"}, function() {
if(chrome.runtime.lastError) {
console.error(chrome.runtime.lastError.message);
}
});
});
JS / save.js
alert("hello world");
就像我在代码中所说的那样,我的pageAction onClick函数中的hello world工作正常。 executeScript方法没有。任何有关正在发生的事情的想法都会有所帮助。
答案 0 :(得分:2)
根据the docs:
要将代码插入页面,您的扩展程序必须为该页面cross-origin permissions。它还必须能够使用
chrome.tabs
模块。您可以使用清单文件的权限字段获得这两种权限。
因此,您需要该网站的权限,即权限字段中的http://example.com/
。
答案 1 :(得分:2)
在我的代码中弄乱了很多不同的东西后,我找到了解决问题的方法。错误似乎在{file: "save.js"}
的行中。当它正在寻找save.js
时,它显然在我的manifest.json
文件所在的顶级目录中查找,而不是在我的代码所在的目录中。我不得不将我的代码更改为{file: "js/save.js"}
,以便找到我的save.js
文件。