Chrome extension for developing communication methods

An overview of the

Chrome extension involves four parts: Web page, Popup, Background, and Content-script. Web pages do not belong to the content of plug-ins, but sometimes pages need to interact with plug-ins. Therefore, the communication between pages and plug-ins is also discussed here.

Note that both Popup and Background run in the context of a plug-in, while Content-script runs in the context of a Web page. For this reason, I’ll break down extension communication into the following scenarios:

  • Communication of scripts within the plug-in:popupandbackgroundCommunication between;
  • webThe page withcontent-scriptThe communication;
  • Plug-in internal scripts withcontent-scriptCommunication between.

These scenarios are described in detail below.

popupwithbackgroundcommunication

Because both run in the same context, in theory, as long as you get each other’s Window object, you can access each other at will, so for the communication between the two, direct examples demonstrate ~

background.js

var popup = chrome.extension.getViews({ type: "Popup"}) [0] / / get popup GetMessageFromBackground (" popup something for my brother ~ ") function GetMessageFromPopup (data) { Console. log("popup something for me ~",data)}Copy the code

popup.js

var background = chrome.extension.getBackgroundPage(); / / / / get the page background Windows object next to do everything ~ background. GetMessageFromPopup (" to my brother background something ") function GetMessageFromBackground(data){console.log(" what background gave me ~",data)}Copy the code

webThe page withcontent-scriptcommunication

The communication between the two brothers is also relatively simple, with window.addeventListener and window.postMessage. Here is an example

// Window.addeventListener ("message",function(ev){console.log(ev.data)}) // Window.postMessage (data,"*")Copy the code

Plug-in internal scripts withcontent-scriptcommunication

Communication between the two is provided by chrome API chrome. Runtime. SendMessage \ chrome runtime. OnMessage. AddListener, both between each other hair message, but it is important to note that The current user sends a message to the latter via the Chrome.tabs. SendMessage API, as shown in the following example:

The receiving end

chrome.runtime.onMessage.addListener(function (msg, sender, response) {
  console.log(msg, sender);
  response();
});
Copy the code

Content-script Sends an internal script to the plug-in

Chrome. Runtime. SendMessage (" data ", function () {the console. The log (" response "); });Copy the code

The internal plug-in script is sent to the Content-script

SendMessage (tabId, "data", function () {console.log(" received response "); })Copy the code