Chrome扩展及应用开发 入门笔记(五)消息机制

简介

Chrome提供了4个有关扩展页面间相互通信的接口,分别是


1.  runtime.sendMessage、runtime.onMessage(可以在content_scripts中运行,所以扩展的其他页面也可以同content_scripts相互通信)
2.  runtime.connect和runtime.onConnect(不可以在content_scripts中运行为更高级的接口,在http://developer.chrome.com/extensions/extension得到有关这两个接口的完整官方文档。)


runtime.sendMessage完整的方法为:

chrome.runtime.sendMessage(extensionId, message, options, callback)
其中extensionId为所发送消息的目标扩展,如果不指定这个值,则默认为发起此消息的扩展本身;

1. Content script 给 popup.js发消息(二者之间通信)

content.js
<pre style="font-family: 宋体; font-size: 9pt; background-color: rgb(255, 255, 255);"><pre name="code" class="javascript">function test() {
   chrome.extension.sendMessage({cmd: "fromcontentscript"}, function (response) {
      alert( "fromcontentscript");
      if (response.frompopup) {
         alert(response.frompopup);
      }

   });
}

 
 
 
 
popop.js

chrome.extension.onMessage.addListener(//直接接受popup发来的消息
		function(request, sender, sendResponse) {
			if (request.cmd == "fromcontentscript")
				sendResponse({frompopup: "popup 接受到了来自contetn script的消息"})
			else
				sendResponse({frompopup: "不告诉你"})
		});
注:  发送方的  cmd: "fromcontentscript" 与 接收方的   request.cmd == "fromcontentscript" 对应;
         发送发收到的消息回复 response.frompopup 与 接收方的响应 sendResponse({frompopup: "popup 接受到了来自contetn script的消息"}) 对应

2. popup.js 给 Content script  发消息(二者之间通信)

popup.js
function clearRequest() {

	chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
		chrome.tabs.sendMessage(tabs[0].id, {message:"clear"}, function(response) {// popup直接给contentscript发消息
			if(response.result=="ok"){
				//$('#localstorage').innerHTML="";
				var p = document.getElementsByTagName("p");
				p[0].innerHTML="";

			}
		});
	});

}
content.js
chrome.extension.onMessage.addListener(//直接接受popup发来的消息
		function(request, sender, sendResponse) {
			if (request.message == "clear") {
				test();
				sendResponse({result: clearLocalStorage()})
			}
			else
				sendResponse({result: "不告诉你"})
		});

3.  Content script 给 popup.js发消息(通过background作为中转)


作用: content 使用消息  setNewsArr 将数据     newsArray ,   newsArrayCookie 传递给 popUp。

content.js
chrome.extension.sendMessage({cmd: "setNewsArr",'arr':newsArray,'arrCookie':newsArrayCookie},function(response) {
	});

popup.js
chrome.extension.sendMessage({cmd: "getNewsArr"},function(response) {
		if(response.arr){
			var len=response.arr.length;
			for(var i=0;i<len;i++){
				$('body').append("<br>"+response.arr[i]+'<br>');
			}
		}
		if(response.arrCookie){//localstorage
			var lenCookie=response.arrCookie.length;


			for(var i=0;i<lenCookie;i++){
				$('#localstorage').append("<br>"+response.arrCookie[i]+'<br>');
			}

		}
	});//

background.js 先将content发来的内容暂存,再将其转发给popup
$(document).ready(function(){
	//getCurIp();
	try{
	g_newsArr=JSON.parse(''+localStorage['newsArr']);// background.html 页面的localStorage['newsArr']内容
		g_newsArrCookie=JSON.parse(''+localStorage['newsArrCookie']);// background.html 页面的localStorage['newsArr']内容
		g_setclearLocalStorage=localStorage['setclearLocalStorage'];
	}catch(c){}
	chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
		if(request.cmd=='setNewsArr'){
			console.log(request.arr)
			g_newsArr=request.arr;
			g_newsArrCookie=request.arrCookie;
			//g_newsArr+="zpp";//
			localStorage['newsArrCookie']=JSON.stringify(g_newsArrCookie);

			localStorage['newsArr']=JSON.stringify(g_newsArr);



		}else if(request.cmd=='getNewsArr'){
			sendResponse({'arr':g_newsArr,'arrCookie':g_newsArrCookie});
		}
	})
});

参考:

4. popup给background发消息

popop.js
chrome.runtime.sendMessage('Hello', function(response){
    document.write(response);
});

background.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
    if(message == 'Hello'){
        sendResponse('Hello from background.');
    }
});

结果 : 点击popup时,出现  Hello from background

ps:


1]   

chrome.runtime.sendMessage({cmd: "setNewsArr2"},function(response) {
chrome.extension.sendMessage({cmd: "setNewsArr"},function(response) {

给background 发消息;

background中可以相互使用接收消息
2]  消息分类

A :一次性消息(one-time requests)
从content script发送给background:
chrome.runtime.sendMessage({cmd: "mycmd"}, function(response) {  console.log(response); });


从background向content script发送消息:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {  chrome.tabs.sendMessage(tabs[0].id, {cmd: "mycmd"}, function(response) {    console.log(response);  }); });


接受消息时一致;



B: 长效消息(long-lived connections)是现在消息的收发双方建立通道,然后通过这个通道收发消息。
连接主动方:
var port = chrome.runtime.connect({name: "con1"}); port.postMessage({cmd:


C: 扩展间消息(cross-extension messages)是在不同的扩展之间收发消息。

相关推荐
©️2020 CSDN 皮肤主题: 技术工厂 设计师:CSDN官方博客 返回首页
实付 49.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值