我所建造的同˚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