Chrome 插件开发(二)- content.js与background.js之间互相通信

这篇文章发表于 阅读 1

一、content向background发送消息

// content.js chrome.runtime.sendMessage(data, (response) => { console.log(response) });
//background.js chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { sendResponse("ok") })

其中 sendResponse 必须调用,不然插件会报错

二、background向content发送消息

// background.js chrome.tabs.sendMessage( tabId, data, response => { console.log(response) } )

tabId指定需要发送到的窗口id

//content.js chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { sendResponse("ok"); });