gpt4 book ai didi

javascript - 唤醒事件页面时如何防止/检测处理和恢复存储数据之间的竞争条件

转载 作者:行者123 更新时间:2023-11-29 10:39:40 31 4
gpt4 key购买 nike

我正在使用 sendMessageonMessage 监听器(在后台和内容页面中),我看到一些消息丢失了。我有一些“全局”变量,每次进入挂起状态时都会存储这些变量,并在脚本启动时首先恢复它们(我首先注册处理程序)。但是,考虑到 chrome.storage 是异步的,我怀疑在我加载全局状态之前正在处理消息(因此出现丢失消息的情况)。

以下是相关代码。

# Register some important listeners.
chrome.alarms.onAlarm.addListener(onAlarm);
chrome.runtime.onMessage.addListener(onMessage);

# Define global variables.
var tabIdList = new Array();
var keepAlives = new Array();
keepAlives["myTab1"] = -1;
keepAlives["myTab2"] = -1;
tabIdList["myTab1"] = -1;
tabIdList["myTab2"] = -1;

# Reload previously stored state of global variables...
reloadGlobalVariable();


# Handle received messages, anytime a message is received,
# set keepAlive for the tab that sends the message.
#
function onMessage(msg, sender) {
if (sender.tab) {
if (msg.message === "hello") {
recordNewTab(msg.tabName, sender.tab.id);
}
keepAlive(msg.tabName, sender.tab.id);
}

function recordNewTab(tabName, tabId) {
tabIdList[tabName] = tabId;
}

function keepAlive(tabName, tabId) {
if (tabIdList[tabName] == tabId) {
keepAlives[tabName] = 1;
}
}


chrome.runtime.onSuspend.addListener(function() {
storeGlobalState();
});


function onAlarm(alarm) {
for (var key in tabIdList) {
if (tabIdList[key] != -1) {
if (keepAlives[key] == -2) {
removeTabRecord(key);
} else {
--keepAlives[key];
sendMessage(key, "ping"); // content pages respond to this message
}
}
}
storeGlobalState(); // probably unnecessary.
}

如何确保 onAlarm 仅在全局变量已重新加载时才继续处理?

我使用异步的 chrome.storage.local.set/get

在此处获取有关挂起/唤醒状态的调试提示的原始问题...

How to debug background/event page suspended state

最佳答案

好吧,对于事件页面处理和 Chrome 存储 API 的异步性质,您无能为力。在异步 JS 中没有“延迟到”。

因此,您需要凑合使用回调。这应该有效:

var globalsReady = false;

chrome.foo.onBar.addListener(handler);

function handler(a, b, c) {
restoreGlobals(function() {
/* Do actual handling using a, b, c */
});
// Special note for onMessage: if you are sending a reply asynchronously,
// you'll need to return true; here
}

function restoreGlobals(callback) {
if(!globalsReady) {
chrome.storage.local.get(/*...*/, function(data) {
/* restore globals here */
globalsReady = true;
if(typeof callback == "function") callback();
});
} else {
// Already done restoring
if(typeof callback == "function") callback();
}
}

restoreGlobals();

关于javascript - 唤醒事件页面时如何防止/检测处理和恢复存储数据之间的竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31416248/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com