欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > Chrome 扩展 background 与content_script 之间通信

Chrome 扩展 background 与content_script 之间通信

2025/4/18 19:01:23 来源:https://blog.csdn.net/testcs_dn/article/details/139514144  浏览:    关键词:Chrome 扩展 background 与content_script 之间通信

content_script 向 background 发消息要用:chrome.runtime.sendMessage

        chrome.runtime.sendMessage({event: "xhr", data:option }, function (res) { //option.onload(res);//console.log(res);if (res.event == "xhr" && !res.err){option.onload(res);}});

background 接收消息:chrome.runtime.onMessage.addListener

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {if (message.event == "copy") {//alert("copy detected");//return true;}sendResponse({});return true; 
});

background 向 content_script 发消息要用:chrome.tabs.sendMessage

            chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {if (tabs && tabs.length > 0) {const activeTab = tabs[0];console.log('当前活动标签页的是:', activeTab);try {chrome.tabs.sendMessage(activeTab.id, {'evt':'mediaUrl','data':mediaUrl }, function (res) { console.log(res);});} catch (error) {console.error(error.message);}}});

content_script 接收消息用:chrome.runtime.onMessage.addListener

和background中是一样的,注意其中的 sendResponse({});

这一句很关键,接收到了就要给一个回应;

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词