![](/img/trans.png)
[英]How to access to object in background page from popup in Chrome extension
[英]How do I send a message from the background to a popup in a Chrome extension everytime a page gets loaded?
我可以通過以下方式從彈出窗口向后台發送消息:
背景.js
chrome.runtime.onMessage.addListener(
function(request) {
alert(request.data.subject);
}
);
彈出窗口.js
chrome.runtime.sendMessage({
msg: "something_completed",
data: {
subject: "Loading...",
content: "Just completed!"
}
});
警報加載正常,但我需要做相反的事情。 我希望后台在加載頁面時發送 api 調用並將該 api 調用的結果發送到 popup.js 以便它可以對 DOM 進行更改。 當我切換上面的代碼時,沒有顯示警報。 我的manifest.json
:
{
"name": "example",
"version": "0.0.1",
"description": "Chrome Extension's message passing example",
"browser_action": {
"default_icon": "images/get_started32.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"content_scripts":[{
"matches":["http://*/*", "https://*/*"],
"js":["popup.js"]
}],
"permissions": [
"background","webRequest","webRequestBlocking","webNavigation","tabs","notifications"
],
"manifest_version": 2
}
從技術上講, chrome.runtime.sendMessage會向包括彈出窗口在內的所有擴展頁面發送一條消息,但這不是通信的組織方式。
請注意,彈出窗口僅在顯示時運行,因此如果它被隱藏,則無法接收消息。
假設彈出窗口已經可見,解決方案通常是使用return true
簡單地等待后台腳本的響應。
popup.js 發送一條消息:
chrome.runtime.sendMessage({foo: 'bar'}, response => {
// use the response here
});
后台腳本:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.foo === 'bar') {
doSomeProcessing(msg).then(sendResponse);
return true;
}
});
function doSomeProcessing(msg) {
return new Promise(resolve => {
// do something async
resolve({data: 123});
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.