背景
Chrome Extension簡單定義爲瀏覽器的功能性擴展,由html、css、js和一個描述文件manifest.json組成,在瀏覽器的地址欄邊上顯示擴展圖標。本質上其實就是一個由html、css、js、圖片等資源組成的一個.crx後綴的壓縮包。
問題
由於最近業務需要,不得不去了解一些相關內容。在實踐的過程中,遇到問題,每當用戶更改他所關注的標籤時,用戶瀏覽器中所有加載的標籤都會根據需要更改圖片icon。
從
到
解決思路
1、background.js定義監聽事件addListener
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { let re = new RegExp("^(http|https)://", "i"); //manifest.json 不設定 tabs permission 的情況下,若 permissions 有設定 url rule,符合條件的 url,tab.url 也會有資料 if (changeInfo.status === "complete" && re.test(tab.url)) { showActionPage(tab); } });
2、當頁面加載完成的時候,進行判斷
function showActionPage(details) { let url = details.url, //URL API urlObject = new global.URL(url), //hostname - 用它取得 amazon marketplace locale hostName = urlObject.hostname, marketplace = new global.AmazonMarketplace("", hostName), locale = marketplace.getLocale().toUpperCase(), menuType, canLoadExtension = helper.checkLoadExtensionUrl(url);
3、符合條件的對icon進行設置
//icon 變成藍色 chrome.browserAction.setIcon({ tabId: details.id, path: { "16": "icon/browser/browser_icon_16.png", "48": "icon/browser/browser_icon_48.png", "64": "icon/browser/browser_icon_64.png", "128": "icon/browser/browser_icon_128.png" }