Chrome瀏覽器支持擴展(Extension)開發,來定制擴展現有的功能,如:自動登錄,定時刷新,搶票等功能,本文以一個簡單的小例子,簡述Google Chrome 擴展開發的基本步驟,僅供學習分享使用。
什么是Chrome擴展?
Chrome擴展使用HTML、JavaScript、CSS和圖片等Web技術開發,用以增強Chrome瀏覽器功能的一種程序。Chrome擴展並不是插件,擴展無需了解瀏覽器的源代碼,只需要Web相關開發技術即可,而插件是更底層的瀏覽器功能擴展,需要深入掌握瀏覽器的源代碼。
Chrome擴展組成部分
Chrome擴展,至少包括一個manifest.json和一個js文件
- manifest.json是擴展的調度中心,用於聲明各種資源。該文件采用JSON格式定義
- js文件中定義要執行的操作
Chrome擴展,通常還可以包括圖標、頁面和CSS等資源
- 圖標通常是19px*19px的PNG文件
- 頁面通常是HTML文件,用於定義顯示給用戶的窗口,如popup頁面或options頁面等【注意】:控制popup窗口或options窗口的分別是popup.js和options.js文件
- CSS是常見的定義頁面樣式的文件
作為一個Google Chrome擴展,上述所有文件應該都位於一個根目錄之下,各個不同類型的文件可以位於不同的子目錄下。
Chrome擴展部署運行
Chrome擴展作為瀏覽器的一部分而存在,運行無需依賴任何Web服務器。通過Chrome 瀏覽器打開chrome://extensions頁面可以查看當前Chrome 瀏覽器部署的全部擴展,或者通過Chrome 瀏覽器的“ ->更多工具->擴展程序”打開。
開啟【開發者模式】,然后【加載已解壓的擴展程序】即可進行運行調試程序,如果修改了程序,可以點擊【重新加載】更新程序。chrome://extensions頁面如下:
示例效果圖
本例主要是監控某網站某件商品是否存在且是否有貨,如果存在,則加入購物車 。Chrome擴展加載后,就會在瀏覽器地址欄右邊,顯示圖標,單擊顯示popup頁面,如下所示:
Chrome瀏覽器擴展還有配置選項頁面,用於擴展說明,配置相關信息等,通過右鍵圖標按鈕-->選項打開對應頁面,或者在擴展詳細信息-->擴展程序選項進行打開,如下所示:
核心代碼
本例主要核心文件有manifest.json,如下所示:

1 { 2 "manifest_version": 2, 3 "name": "iSmoking", 4 "version": "1.0.0", 5 "description": "iSmoking監控程序", 6 "icons": 7 { 8 "16": "img/smoking.png", 9 "48":"img/smoking.png", 10 "128": "img/smoking.png" 11 }, 12 "background": 13 { 14 "scripts": ["js/jquery-3.5.1.min.js","js/background.js"] 15 }, 16 "browser_action": 17 { 18 "default_icon": "img/smoking.png", 19 "default_title": "iSmoking監控程序", 20 "default_popup": "popup.html" 21 }, 22 "content_scripts": 23 [ 24 { 25 "matches": ["https://www.smokingpipes.com/*"], 26 "js": ["js/jquery-3.5.1.min.js", "js/content.js"], 27 "run_at": "document_end", 28 "all_frames":true 29 } 30 ], 31 "permissions": 32 [ 33 "contextMenus", 34 "tabs", 35 "notifications", 36 "webRequest", 37 "webRequestBlocking", 38 "storage", 39 "https://www.smokingpipes.com/*" 40 ], 41 "options_ui": 42 { 43 "page": "options.html", 44 "chrome_style": true 45 } 46 }
其中browser_action 用於配置適用於整個瀏覽器對象的功能,如果只針對某一個頁面生效,可以使用page_action , 且二者不可以並存。
Popup頁面即點擊圖標彈出的對應的頁面,可以引用JS進行業務處理,也可以和Background(后台一直存在的程序)或者 ContentScript(用戶操作Dom)進行通信。

1 <!doctype html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 5 <title>iSmoking監控</title> 6 <link rel="stylesheet" href="css/popup.css"> 7 <script src="js/jquery-3.5.1.min.js"></script> 8 <script src="js/popup.js"></script> 9 </head> 10 <body> 11 <h1>iSmoking監控</h1> 12 <div id="option"> 13 <span>當前用戶名:</span> <input type="text" name="username" id="username" class="txt" readonly><br /></span> <input type="hidden" name="password" id="password"><br /> 14 <span>當前商品Id:</span> <input type="text" name="itemid" id="itemid" class="txt" readonly><br /> 15 <span>監控數量:</span> <input type="text" name="count" id="count" class="txt" readonly><br /> 16 </div> 17 <div> 18 19 <input type="button" value="" name="start" id="start" class="button start"> 20 <input type="button" value="" name="stop" id="stop" class="button stop"> 21 </div> 22 23 </body> 24 </html>
Popup和Content進行通信,

1 $(function () { 2 var keys = ["ismoking_username", "ismoking_password", "ismoking_itemid","ismoking_count","ismoking_status"]; 3 //從storage中獲取之前保存的內容 4 $("#username").val(localStorage.getItem(keys[0])); 5 $("#password").val(localStorage.getItem(keys[1])); 6 $("#itemid").val(localStorage.getItem(keys[2])); 7 $("#count").val(localStorage.getItem(keys[3])); 8 $("#start").click(function () { 9 var key_msg={"ismoking_username":localStorage.getItem(keys[0]), "ismoking_password":localStorage.getItem(keys[1]),"ismoking_itemid":localStorage.getItem(keys[2]),"ismoking_count":localStorage.getItem(keys[3]),"ismoking_status":"begin"}; 10 console.log(JSON.stringify(key_msg)); 11 sendMessageToContentScript(key_msg,function(msg){ 12 console.log("收到成功"+msg); 13 }); 14 15 }); 16 $("#stop").click(function () { 17 var key_msg={"ismoking_username":localStorage.getItem(keys[0]), "ismoking_password":localStorage.getItem(keys[1]),"ismoking_itemid":localStorage.getItem(keys[2]),"ismoking_count":localStorage.getItem(keys[3]),"ismoking_status":"stop"}; 18 console.log(JSON.stringify(key_msg)); 19 sendMessageToContentScript(key_msg,function(msg){ 20 console.log("收到成功"+msg); 21 }); 22 }); 23 }); 24 25 // 獲取當前選項卡ID 26 function getCurrentTabId(callback) 27 { 28 chrome.tabs.query({active: true, currentWindow: true}, function(tabs) 29 { 30 if(callback) callback(tabs.length ? tabs[0].id: null); 31 }); 32 } 33 34 // 向content-script主動發送消息 35 function sendMessageToContentScript(message, callback) 36 { 37 getCurrentTabId((tabId) => 38 { 39 chrome.tabs.sendMessage(tabId, message, function(response) 40 { 41 if(callback) callback(response); 42 }); 43 }); 44 }
然后通過ContentScript監聽信息,如下所示:

1 // 接收來自后台的消息 2 chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) 3 { 4 console.log('收到來自 ' + (sender.tab ? "content-script(" + sender.tab.url + ")" : "popup或者background") + ' 的消息:', request); 5 6 for (const key in request) { 7 if (request.hasOwnProperty(key)) { 8 const element = request[key]; 9 localStorage.setItem(key,element); 10 } 11 } 12 // tip(JSON.stringify(request)); 13 sendResponse('我收到你的消息了:'+JSON.stringify(request)); 14 var status = request[keys[4]]; 15 if(status=="begin"){ 16 doing1(); 17 } 18 });
提示:功能實現和前兩篇博客基本一樣,只是實現方式略有差異。關於Chrome擴展的開發文檔,可以參考鏈接 或者 擴展開發極客博客
備注
【宋】朱敦儒
我是清都山水郎,天教分付與疏狂。
曾批給雨支風券,累上留雲借月章。
玉樓金闕慵歸去,且插梅花醉洛陽。