Chrome plug-in: communication between content.js, background.js, options.js, popup.js

content.js sends message to background.js

Message direction:

// content.js 一般不直接与options.js, popup.js 通信,而是与常驻的background.js通信
content.js => [background.js, options.js, popup.js]

Send a message:

// content.js
chrome.runtime.sendMessage({
    
    data: 'Hello'})

Receive message:

// background.js, options.js, popup.js
chrome.runtime.onMessage.addListener(function (message){
    
    
    console.log(message);
})

Reception status:

// background.js message 
{
    
    data: 'Hello'}

// options.js message 
{
    
    data: 'Hello'}

// popup.js message 
{
    
    data: 'Hello'}

background.js sends message to content.js

webextension-polyfillThrough the browser proxy object, chrome can implement Promise


// https://github.com/mozilla/webextension-polyfill
import browser from "webextension-polyfill";

// 获取当前活跃的tab
const tabs = await browser.tabs.query({
    
    
   active: true,
   currentWindow: true,
 });

 if (tabs && tabs.length > 0) {
    
    
   await browser.tabs.sendMessage(tabs[0].id, message);
 }

options.js or popup.js passes data to background.js

background.js defines the receiving function

// background.js
function onMessage(message) {
    
    
  console.log(message);
}

// 注意,如果是模块化打包,需要挂载到全局
window.onMessage = onMessage;


options.js 调用消息接收函数

```js
// options.js 或者 popup.js
const background = chrome.extension.getBackgroundPage();
background.onMessage({
    
     data: "hello" });

received data

// background.js message 
{
    
    data: 'hello'}

Summarize

You can think of background.js as a server or a bridge or a global state manager. Other components communicate with it and access data through background.js. This makes programming much simpler.

content.js <=> background.js <=> [options.js, popup.js]

reference article

  1. Communication between Google Chrome plug-in content_scripts, background, and popup
  2. [Summary] 1798- Several ways of real-time communication with Chrome plug-ins

おすすめ

転載: blog.csdn.net/mouday/article/details/132724867