Javascript 非常简单的Chrome扩展以显示警报
我正在尝试创建一个快速Chrome扩展(完全初学者),只想在单击图标时显示一个警报,因此我尝试了以下方法: manifest.jsonJavascript 非常简单的Chrome扩展以显示警报,javascript,api,google-chrome-extension,Javascript,Api,Google Chrome Extension,我正在尝试创建一个快速Chrome扩展(完全初学者),只想在单击图标时显示一个警报,因此我尝试了以下方法: manifest.json { "name": "Something", "version": "1.0", "manifest_version": 2, "description": "Woohoo", "browser_action": { "default_icon": "icon.png" }, "conten
{
"name": "Something",
"version": "1.0",
"manifest_version": 2,
"description": "Woohoo",
"browser_action": {
"default_icon": "icon.png"
},
"content_scripts" : [{
"matches": ["<all_urls>"],
"js" : ["bgscript.js"]
}]
}
{
"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"]
}]
}
然而,当我点击我的图标时,什么也没发生!综上所述,有人能指出这不起作用的原因吗?为了在点击事件时收到浏览器操作的
通知,您需要一个(或者更好的),而不是
按如下方式更改您的清单:
// Replace that:
"content_scripts" : [{...}]
// with this:
"background": {
"persistent": false,
"scripts": ["bgscript.js"]
}
如果希望浏览器操作调用内容脚本上的内容,则需要使用(例如)通过后台页面进行通信。
例如:
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"]
}]
}
{
"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"]
}]
}
content.js
chrome.browserAction.onClicked.addListener(function(tab) {
alert('icon clicked')
});
chrome.browserAction.onClicked.addListener(function (tab) {
/* Send a message to the active tab's content script */
chrome.tabs.sendMessage(tab.id, { action: 'saySomething' });
});
chrome.runtime.onMessage.addListener(function (msg) {
/* We received a message, let's do as instructed */
if (msg.action === 'saySomething') {
alert('something');
}
});
啊,好的-在网上发现这么多的帖子说要使用“内容脚本”,这导致了我的问题!不过现在可以了,非常感谢:)总是很乐意帮助:)顺便说一句,因为我不确定你是在哪里尝试与背景页面或内容脚本交流,我更新了答案,以涵盖第二种情况。非常感谢更新-看起来我有一些阅读要做,但至少你让我回到正轨!不是我,我比你高!这是一个非常好的回答。我想有人只是在做一些路过下层的事情。今天我自己也做了一些:(但为什么这应该是我的答案?为什么是我?为什么是我?):D