前請說明:本文適用於以前歷來沒有接觸過chrome extension擴展程序的同窗~javascript
chrome_ext_demo
,在項目根路徑(chrome_ext_demo/
)下建立 manifest.json
在manifest.json
中添加以下示例(只是個簡單例子,詳細字段說明可參考官方文檔):html
{ "name":"Chrome Extension demo", "version":"1.0.0", "manifest_version": 2, "description":"Hello chrome extension.", "browser_action":{ "default_icon":"icon.png", "default_popup":"popup.html" }, "web_accessible_resources":[ "icon.png", "popup.js" ], "content_scripts": [ { "matches": ["*://xxx.com/xxx/*"], "js": ["content.js"] } ] }
小小說明一下:
manifest_version
的值必須是2,content_scripts.matches
這個數組中的值表示咱們但願匹配的域名,以*://baidu.com/*
爲例,這個表示只要域名是baidu.com,不論協議是什麼,不論路徑是什麼,這個插件都生效~java
web_accessible_resources
和content_scripts
中填寫的icon.png
、popup.html
、popup.js
、content.js
文件路徑得知,咱們須要在chrome_ext_demo/
下建立如下3個文件(PS:圖片偷了下懶,隨便找了一張圖,不規範>.<)。在popup.html
添加以下代碼:git
<!DOCTYPE html> <html> <head> <style> body{ width:350px; } div{ border:1px solid #eeeaaa; padding:20px; font: 20px normal helvetica,verdana,sans-serif; } </style> <script src="popup.js"></script> </head> <body> <div>123</div> </body> </html>
在popup.js
添加以下代碼:github
function sayHello(){ var message = document.createTextNode("Hello chrome extension!"); var out = document.createElement("div"); out.appendChild(message); document.body.appendChild(out); } window.onload = sayHello;
在content.js
添加以下代碼:web
alert('hi content!');
其中,content.js
是做用在目標域名目標路徑(*://xxx.com/xxx/*
)下的頁面上的。chrome
打開chrome瀏覽器,進入chrome://extensions/
,打開開發者模式,點擊【加載已解壓的擴展程序】,選中chrome_ext_demo文件夾,引入擴展json
在chrome://extensions/
頁面上,點擊【打包擴展程序】,選中咱們須要打包的擴展程序根目錄,點擊打包便可。數組
歡迎訪問個人github倉庫進行下載:https://github.com/silencetea/demo-market/tree/master/chrome_ext_demo瀏覽器