首先我们来看一下chrome能做什么事情,其实主要的功能是往页面注入一段js代码,修改浏览器外观和获取浏览器内部信息。

chrome插件生命周期

  • 浏览器打开时执行一次的js代码

  • 每打开一个页面执行的js代码

  • 点击浏览器上插件按钮,打开一个页面,执行的js代码

开发chrome插件的准备工作

一个文本编辑器即可

一个hello world工程

新建一个文本文件:manifest.json

内容如下:

{
    "manifest_version": 2,
    "name": "优读Uread网页版插件",
    "version": "1.0",
    "description": "测试版",
	"permissions": [
		"tabs"
	],
    "content_scripts": [
        {
            "js": ["index.js"]
        }
    ],
	"browser_action": {
		"default_popup": "index.html"
	},
	"background": {  
		"scripts": ["b.js"]  
	}  
}

  • manifest_version固定写2

  • name是插件的名字

  • version是自定义版本号

  • description是插件的描述

  • permissions是插件要用到的权限列表,如果不写上,则对应的api无法调用,可用权限请参考:http://open.chrome.360.cn/extension_dev/permissions.html

  • content_scripts是每次打开页面执行的js文件

  • browser_action是指定点击插件弹出的页面

  • background是打开浏览器只执行一次的js

往页面注入js实现特定需求

要注意一个问题,content_scripts指定的js的作用域与页面里面js的作用域是不同的,所以无法相互调用,唯一办法就是content_scripts操作页面的dom元素,达到注入js字符串的效果,然后通过注入的js字符串来与页面的js交互。

插件的消息传递

  • 长连接
// chrome插件监听tab页获取userid
chrome.runtime.onConnect.addListener(function(port) {
    port.onMessage.addListener(function(msg) {
      
    });
});

  • 短连接

    chrome.tabs.getSelected(null, function(tab){
       chrome.tabs.sendMessage(tab.id, {target: "tab", "action": "openNowUrl", "html": html}, function(response) {
                    console.log(response);
                });  
    });


chrome.runtime.onMessage.addListener(
    function(msg, sender, sendResponse) {
     
        if(msg.target == 'tab' && msg.action == 'openNowUrl'){
            
            try{
               document.getElementById('openUrlInUread').remove(); 
            }catch(e){
                
            }
            
            var div=document.createElement("div");
            div.innerHTML = msg.html ;
            document.body.appendChild(div);
           sendResponse(msg);
        }
});