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>