我需要将数据从popup.js发送到background.js,然后从background.js发送到popup.js。但如果 popup.html 关闭,它无法从 background.js 接收数据,因为端口不存在。如何解决?
我的代码:
popup.js
var port = chrome.runtime.connect({
name: 'Communication with background.js',
});
port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
console.log("message recieved" + msg);
});
背景.js
chrome.runtime.onConnect.addListener(function(port) {
console.log("Connected .....");
port.onMessage.addListener(function(msg) {
console.log("message recieved " + msg);
port.postMessage("Hi Popup.js");
});
});
最佳答案
一旦弹出窗口消失,不仅端口关闭,而且 popup.js 脚本也不再运行。您可以将内容存储在background.js脚本中(持久),并在每次加载弹出窗口时发送相关信息(您已经部分构建了此信息),或者您可以将信息存储在本地存储中并每次加载它加载弹出窗口的时间。
popup.js 或 background.js
chrome.storage.sync.set({'dataValue1': 'Some data 1.'});
chrome.storage.sync.set({'dataValue2': 'Some data 2.'});
popup.js
function updatePopup(){
chrome.storage.sync.get(['dataValue1','dataValue2'], function(data) {
//Update popupElement1 and popupElement2 with loaded data
document.getElementById("popupElement1").value = data.dataValue1;
document.getElementById("popupElement2").value = data.dataValue2;
});
}
document.addEventListener('DOMContentLoaded', updatePopup);
关于javascript - 如果弹出窗口关闭,如何在background.js和popup.js之间发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56264343/