我正在尝试创建一个快速的Chrome扩展程序(完整的初学者),并且只想在单击该图标时显示警报,所以我尝试了以下操作:
manifest.json
{
"name": "Something",
"version": "1.0",
"manifest_version": 2,
"description": "Woohoo",
"browser_action": {
"default_icon": "icon.png"
},
"content_scripts" : [{
"matches": ["<all_urls>"],
"js" : ["bgscript.js"]
}]
}
bgscript.js
chrome.browserAction.onClicked.addListener(function(tab) {
alert('icon clicked')
});
但是,当我单击图标时,什么也不会发生!综上所述-谁能发现为什么这行不通?
最佳答案
为了通知浏览器操作的onClicked
事件,您需要一个 background-page (或更好的 event-page ),而不是 content-script 。
像这样更改 list :
// Replace that:
"content_scripts" : [{...}]
// with this:
"background": {
"persistent": false,
"scripts": ["bgscript.js"]
}
如果您希望浏览器操作在内容脚本上调用某些内容,则需要使用 Message Passing (例如 Simple one-time requests )在背景页面之间进行交流。
例如。:
manifest.json
{
"name": "Something",
"version": "1.0",
"manifest_version": 2,
"description": "Woohoo",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts" : [{
"matches": ["<all_urls>"],
"js" : ["content.js"]
}]
}
background.js
chrome.browserAction.onClicked.addListener(function (tab) {
/* Send a message to the active tab's content script */
chrome.tabs.sendMessage(tab.id, { action: 'saySomething' });
});
content.js
chrome.runtime.onMessage.addListener(function (msg) {
/* We received a message, let's do as instructed */
if (msg.action === 'saySomething') {
alert('something');
}
});
关于javascript - 非常简单的Chrome扩展程序可以显示警报,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21187377/