Chrome Extension sendMessage & sendRequest【谷歌浏览器扩展之消息通信】

本文介绍了Chrome扩展中content_scripts与background、options_page之间的消息通信。content_scripts在网页中运行,可通过sendMessage与background进行通信。背景页background可以接收到content_scripts的消息,并能通过特定方式发送消息回content_scripts。文章详细阐述了通信过程及其方法。
摘要由CSDN通过智能技术生成

        嗯,标题不是翻译。

        简言 content_scripts 在浏览的网页中运行(注入),background & options_page 在应用里运行,但 content_scripts 可与应用通信,窗体的交互参考前面提供的文档或官方的图和介绍这里不赘述。


       前后台消息通信,刚开始接触时使用一些文档中提供的方法用不了。前后台的发送、接收消息的方式不同,长连接参考开发文档(文档中有的发送方式已不能使用了,下面的可用):

       从 content_scripts 发送消息或处理的数据发送给 background 时:

//content_scripts 发送消息给 background 
var oimgs = document.getElementsByTagName('img');
chrome.runtime.sendMessage({msg: 'send', imgs: oimgs}, function(response) {
	if(response){ //使用 response.status 如果返回的数据为空或不存在此值会报错
		//alert('完成');
	}
});


        background 接收来自 content_scripts 的消息

//background 接受来自 contentscript 的消息
var ocurTabId;
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值