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 用法详
- 下一篇: FPGA在各行业的应用分析