chrome 插件开发心得
最近一個多月都在開發chrome的插件, 從無到有, 算是了解部分了! 說下chrome開發前需要具備的基本東西吧:
在做插件時 我的H5是屬于基本不會的! 也是查閱大量的資料, 邊做邊學,才終于將公司要的插件開發出來!
說下插件開發吧
怎么才知道我需要什么文件 background.js, content_script.js, popup.js文件的創建是根據實際情況的
在這之前 先要在manifest.json里面獲取權限
"permissions" : ["alarms","tabs","https://*/*","*://*/*","http://*/*"],"content_scripts":[{"matches":["https://*/*","*://*/*",],"js":["lib/jquery-2.0.0.min.js", "content_script.js"],"run_at": "document_end"}] 復制代碼background.js, content_script.js, popup.js文件之間的通訊, 這里只是做講了發送一次消息的. 發送多次消息,也就是長連接和這個區別不大, 只是改了部分等下,這個百度是可以搜索到的,我就不說了
#content_script.js可以做的事情
###1. content_script.js向background.js發送消息
// 這里要先獲取在那個標簽頁面 chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {// 這里也可以知道當前標簽頁的URL tabs[0].urlchrome.tabs.sendMessage(tabs[0].id, { message: "begin"}, function (response) {});});; 復制代碼###2. content_script.js向popup.js發送消息
// 這里使用的是extension chrome.extension.sendMessage({msg: "message"},function (response) {// response 是background 收到消息后的返回數據if (response !== undefined) {}}); 復制代碼###3. content_script.js接收來自popup和background的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendRequest) {// request 你收到的內容,// sender 可以獲取到你的tab的url// sendRequest 收到消息后回調發送消息的人 也就是上面response得到東西 }); 復制代碼#background.js可以做的事情
###1. background向content_script.js發送消息
// 這里使用的是runtime chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {chrome.tabs.sendMessage(tabs[0].id, { message: "begin"}, function (response) {});});; 復制代碼###2. background 向popup.js發送消息
// 在background里面定義變量data var data = "我是數據" 復制代碼// 在popup.js里面 // popup.js是可以直接獲取到background里面的數據 var data = chrome.extension.getBackgroundPage().data; console.log(data); 復制代碼###3. background接收來自popup和content_script.js的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendRequest) {// request 你收到的內容,// sender 可以獲取到你的tab的url// sendRequest 收到消息后回調發送消息的人 也就是上面response得到東西 }); 復制代碼#popup.js可以做的事情
###1. popup.js向content_script.js發送消息
// 這里要先獲取在那個標簽頁面 chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {// 這里也可以知道當前標簽頁的URL tabs[0].urlchrome.tabs.sendMessage(tabs[0].id, { message: "begin"}, function (response) {});});; 復制代碼###2. popup.js 向background發送消息
chrome.extension.sendMessage({msg: "message"},function (response) {// response 是background 收到消息后的返回數據if (response !== undefined) {}}); 復制代碼###3. popup接收來自content_script.js的消息
//使用extension chrome.extension.onMessage.addListener(function(request, sender, sendRequest) {// request 你收到的內容,// sender 可以獲取到你的tab的url// sendRequest 收到消息后回調發送消息的人 也就是上面response得到東西 }); 復制代碼更新當前頁面的url
chrome.tabs.query({currentWindow: true, active: true}, function (tabs) {chrome.tabs.update(tabs[0].id, {url: "https: www.baidu.com"});}); 復制代碼以上內容基本可以解決插件開發的基本問題了, 其他的api 可以進入Google的開發者網站查詢!
轉載于:https://juejin.im/post/5a41ae82f265da431876fdbe
總結
以上是生活随笔為你收集整理的chrome 插件开发心得的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 68.connect-flash 用法详
- 下一篇: 3.C#知识点:is和as