background.js发消息给content-script
background.js发送
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){ chrome.tabs.sendMessage(tabs[0].id, {message:"calculate"}, function(response) { if(typeof response !='undefined'){ alert(response); }else{ alert("response为空=>"+response); } });//end sendMessage }); /
content-script接收
chrome.extension.onMessage.addListener( function(request, sender, sendResponse) { alert("前端/后端/Popup收到"); sendResponse("popup返回值"); } );
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> <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>
- THE END -
最后修改:2020年9月9日