background.js发消息给content-script
background.js发送
chrome
.tabs
.query({
active
: true,
currentWindow
: true
}, (tabs
) => {
let message
= {
info
: window
.localStorage
.getItem('isShow')
}
chrome
.tabs
.sendMessage(tabs
[0].id
, message
, res
=> {
console
.log('bg=>content')
console
.log(res
)
})
})
content-script接收
chrome
.runtime
.onMessage
.addListener((request
, sender
, sendResponse
) => {
console
.log(request
.info
)
sendResponse('get the message')
})
content-script发消息给background.js
content-script发送
Chrome提供的大部分API是不支持在content_scripts中运行 sendMessage onMessage 是可以使用
chrome
.runtime
.sendMessage({
info
: isShow
}, res
=> {
})
background.js接收
chrome
.runtime
.onMessage
.addListener((req
, sender
, sendResponse
) => {
const res
= req
.info
console
.log(res
)
})
补充
background给popup发消息
function toPopup () {
alert('to popup')
}
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>
转载请注明原文地址:https://ipadbbs.8miu.com/read-26632.html