chrome扩展中,content-script与background.js之间的通信

    技术2022-07-15  74

    background.js发消息给content-script

    background.js发送 // bg---->content chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { let message = { //这里的内容就是发送至content-script的内容 info: window.localStorage.getItem('isShow') } chrome.tabs.sendMessage(tabs[0].id, message, res => { console.log('bg=>content') console.log(res) }) }) content-script接收 // get popup2content info chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { console.log(request.info) // 这里是返回给bg的内容 sendResponse('get the message') })

    content-script发消息给background.js

    content-script发送

    Chrome提供的大部分API是不支持在content_scripts中运行 sendMessage onMessage 是可以使用

    chrome.runtime.sendMessage({ info: isShow }, res => { // 答复 // alert(res) }) background.js接收 chrome.runtime.onMessage.addListener((req, sender, sendResponse) => { const res = req.info console.log(res) })

    补充

    background给popup发消息 // background.js中 function toPopup () { alert('to popup') } // popup.js中 const bg = chrome.extension.getBackgroundPage() document.getElementById('btn').onclick = function () { bg.toPopup() } popup.html中 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <button id="btn">click</button> <script src="./popup.js"></script> </body> </html>
    Processed: 0.011, SQL: 9