我所建造的同˚F为我的镀铬扩展提供了一个特征。 (谷歌搜索时来解决这个:)这么多的名字),这将创建一个ON/OFF开关/切换 我用下面的方法应用和内容的脚本之间的按摩:
清单
将所有的页面(hover.js)我的内容脚本和运行我extention脚本(background.js)
....
"browser_action": {
"default_icon": {
"19": "icons/icon-active.png"
}
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"css": ["css/hover.css"],
"js": ["js/hover.js"]
}
],
"background" : { "scripts": ["js/background.js"] },
....
背景。JS
在这里,我们prepering后台脚本(这在所有Chrome窗口运行)来发送和收到extention状态
// start extention as active
var status = true;
// set toggle of extention on browser action click and notify content script
chrome.browserAction.onClicked.addListener(function(tabs) {
if (status == 'true'){
status = false;
chrome.browserAction.setIcon({path: "icons/16x16.png"});
}
else{
status = true;
chrome.browserAction.setIcon({path: "icons/icon-active.png"});
}
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {status: status});
});
});
// check status on tab update and notify content script
chrome.tabs.onActivated.addListener(function() {
if (status == 'true'){
chrome.browserAction.setIcon({path: "icons/icon-active.png"});
}
else{
chrome.browserAction.setIcon({path: "icons/16x16.png"});
}
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {status: status});
});
});
//send extention status on request
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.status == "getStatus")
sendResponse({status: status});
});
正如你可以看到有3个功能:
更改浏览器操作按钮单击的状态。
当您移动到不同的选项卡并通知内容脚本时(每个选项卡具有内容脚本的自己“实例”,因此在一个选项卡中禁用可能仍然在另一选项卡中处于活动状态)时,请检查状态。
根据内容脚本的请求发送状态响应。
内容脚本
// check extention status
chrome.runtime.sendMessage({status: "getStatus"}, function(response) {
if (response.status == 'true'){
// check elements mouse is hover
document.addEventListener("mouseover", setLink, true);
}
else{
document.removeEventListener("mouseover", setLink, true);
}
});
// wait for massage from background script
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.status == 'true'){
// check elements mouse is hover
document.addEventListener("mouseover", setLink, true);
}
else{
document.removeEventListener("mouseover", setLink, true);
}
});
每个内容的脚本应首先通过发送按摩到后台脚本检查进一步扩展的地位和收到的状态更新。另外,如果我们在一个选项卡中关闭扩展,当我们更改选项卡时,我们将通知更改的内容脚本。
我敢肯定,这可以在脚本方面来更好的做,但我希望这将有助于...
被添加到页面的图标,或者你的意思是你看到的扩展图标在浏览器工具栏中? – Archer
我想到了浏览器工具栏。 – vermotr
然后,您需要随时包含脚本,但只有在单击按钮时才调用您想要运行的任何功能。你不会有条件地包括一些东西 - 你总是包括它。 – Archer