chrome插件

378 阅读1分钟

1、Contentscript注入到Webpage

2、原始web+注入的的content_scripts=新的web页面。当打开多个web页面时,就会存在多个新的web页面,因为每个页面都注入content_scripts。

3、Background插件运行环境,可以html+js,也可以单独的js,插件启动后就常驻后台,只有一个。这类脚本是运行在浏览器后台的,注意它是与当前浏览页面无关的。

chrome.browserAction.setIcon({path: ''})
chrome.browserAction.onClicked.addListener(function(){
})
chrome.tabs.query({},function(tabs){
})
chrome.tabs.sendRequest(tab.id,{},function(){
})
chrome.tabs.create({}, function(){})
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
	sendResponse({xxx:'xxx'})
})


chrome.extension.sendRequest({xxx:'xxx'})
chrome.runtime.getManifest().version
chrome.runtime.onRequest.addListener(function(data, sender, sendResponse){
})


chrome.storage.local.get(key, function(data){})
chrome.storage.local.set({})
chrome.storage.sync.set({})
chrome.tabs.captureVisibleTab(null, {}, function(){})
chrome.runtime.onInstalled.addListener(function(){})
chrome.runtime.onConnect.addListener(function(port){
})


manifest.json
{
	name: 'xxx',
    manifest_version: 2,
	background: {},
    content_scripts: [
    	{
        	js: [],
            css: [],
        	matches: [],
            exclude_matches: [],
            all_frames: true,
            
        }
    ],
}

content_scripts --> background

content_scripts主动给background发送信息

chrome.runtime.sendMessage(
    {greeting: message || '你好,我是content-script呀,我主动发消息给后台!'},
   function(response) {
        tip('收到来自后台的回复:' + response);
    }
);

在发出方是主动发送消息,那么接收方必须时刻准备接受消息,才能保证及时接收到,所以接收方都是通过监听这一动作来完成消息的接收

// 监听消息

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
{
     // code...
     sendResponse('我已收到你的消息:' +JSON.stringify(request));//做出回应
});

注:长连接,chrome.runtime.onConnect.addListener

bg给content_scripts发送信息

发送消息一般是先获取到tabID在发送消息 // bg获取当前选项卡ID

function getCurrentTabId(callback){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        if(callback) callback(tabs.length ? tabs[0].id: null);
    });
}
function sendMessageToContentScript(message, callback){
    getCurrentTabId((tabId) =>{
        chrome.tabs.sendMessage(tabId, message, function(response){
            if(callback) callback(response);
        });
    });
}
sendMessageToContentScript('你好,我是bg!', (response) => {
        if(response) alert('收到来自content-script的回复:'+response);
});

content_scripts接收消息 chrome.runtime.onMessage.addListener

popup调用后台脚本中的方法

var bg = chrome.extension.getBackgroundPage();
bg.test();//test()是background中的一个方法