Content_scripts, Background, popup, etc

1.content_scriptsandbackgroundThe communication

  • Receiving messages:chrome.runtime.onMessage.addListener
  • Send a message:chrome.runtime.sendMessage
  1. We first incontent_scriptsAdd a button to trigger the event

contentJs/index.js

//contentJs/index.js
const but2 = $('')
// Add a button button
page.append(but2)
$('body').append(page)
// Click the event
$('#cj_but2').click(function (e) {
    // Click the button to send the message
    chrome.runtime.sendMessage({
        info: "I'm Content.js, I'm sending a message."
    }, res= > {
        console.log('I'm Content.js and I got a message:', res)
    })
})
// Receive the message
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log(request, sender, sendResponse)
    sendResponse('I got your message! ');
});
Copy the code
  1. inbackground.jsThe page receives and sends messages

background.js

//background.js
// Receive the message
chrome.runtime.onMessage.addListener(async (req, sender, sendResponse) => {
    console.log('I'm background and I received a message from Content.js:', req.info)
    sendResponse('Hahaha')
    const tabId = await getCurrentTabId()
    // To send a message on the background page, the current tabID is required
    chrome.tabs.sendMessage(tabId, 'I'm background, I'm sending a message'.function (res) {
        console.log('background:, res)
    });
})
/** * Get the current TAB ID */
function getCurrentTabId() {
    return new Promise((resolve, reject) = > {
        chrome.tabs.query({ active: true.currentWindow: true }, function (tabs) {
            resolve(tabs.length ? tabs[0].id : null)}); })}Copy the code
  1. Refresh the plug-in and the page

There’s a button

  1. Click the button to trigger the event

  2. Output information in the console of a page

  1. Output information in the console of the background page

2,background.jsDisplayed in the upper right cornercommunication

  • In the background:chrome.extension.getViews()Gets an array of Windows for each running page in the current plug-in ([window, window])
  • In the dialog box displayed in the upper right corner:chrome.extension.getBackgroundPage()Get the window object of the background page
  1. background.jsAdd the following code to the
//background.js
/** * communication function */
function backFun () {
    console.log('the arguments:.arguments)
    const allViews = chrome.extension.getViews()
    console.log('chrome. The extension. GetViews () :', allViews)
}
Copy the code
  1. index.jsTo comment out our previous timer, alert affects the flow, and then change the button click event, get the window object of the background page, and call
// index.js
const background = chrome.extension.getBackgroundPage();
console.log(background)
plugin_search_but.onclick = function () {
    // alert('plugin_search_inp '=' + plugin_search_inp.value.trim() ')
    background.backFun('This is argument one'..'This is argument 2'.)}Copy the code
  1. Refresh the plug-in
  2. Click on the top righticon
  3. Right-click the element to open the popup page’s console == and the background page’s console is not a ==
  4. Click on the button

The plug-in console displays below

Console display on background page

Displays a function call console value and an array of Window objects

3,Pop-up box in the upper right cornerandcontent_scriptsCommunication between

  • A dialog box is displayed in the upper right corner:chrome.tabs.connect, the linkcontent_scriptsScript communication
  • Content_scripts:chrome.runtime.onConnect
  1. In the firstcontent_scriptsaddchrome.runtime.onConnectListening links are used:

contentJs/index.js

// `contentJs/index.js`
chrome.runtime.onConnect.addListener((res) = > {
    console.log('ContentJS chrome.runtime.onConnect:',res)
    if (res.name === 'myConnect') {
        res.onMessage.addListener(mess= > {
            console.log('the res contentjs. OnMessage. AddListener:', mess)
            res.postMessage('Ha ha ha, I'm contentjs')})}})Copy the code
  1. Again inThe index.js dialog box is displayed in the upper right cornerTo establish a link:

index.js

Change our button event to our message trigger event

// index.js
plugin_search_but.onclick = function () {
    // alert('plugin_search_inp '=' + plugin_search_inp.value.trim() ')
    // background.backfun (' this is argument 1', 'this is argument 2')
    mess()
}
async function mess () {
    const tabId = await getCurrentTabId()
    const connect = chrome.tabs.connect(tabId, {name: 'myConnect'});
    console.log(connect)
    connect.postMessage('Here's the popup page. Who are you? ')
    connect.onMessage.addListener((mess) = > {
        console.log(mess)
    })
}

/** * Get the current TAB ID */
function getCurrentTabId() {
    return new Promise((resolve, reject) = > {
        chrome.tabs.query({ active: true.currentWindow: true }, function (tabs) {
            resolve(tabs.length ? tabs[0].id : null)}); })}Copy the code
  1. Refresh the plug-in
  2. Click on the top right corner of the pluginicon
  3. Right-click in the plug-in pop-up to open the console
  4. Click the button to perform the operation

Plug-in popup console displays:

The console on the page shows:

Now, somebody wants to ask, this is a popup in the upper right corner talking to content_scripts, what about content_scripts talking to a popup in the upper right corner?

The pop-up box only needs to be clicked on the plug-in to pop up, and when you operate the page, the plug-in box will disappear again… After disappearing, the.js of the popbox will be destroyed…. So, you can go tobackgroundCommunicate and then click popup after the popup box andbackgroundCommunicate, or pop up after direct tocontent_scriptscommunication

reference
  • Google Chrome plugin official page
  • Develop Google Chrome plugins from zero to one

Denver annual essay | 2020 technical way with me The campaign is under way…