gpt4 book ai didi

javascript - 是什么导致我的 chrome 扩展程序的 background.js 卡住并且不响应消息

转载 作者:行者123 更新时间:2023-11-29 10:44:51 25 4
gpt4 key购买 nike

每隔一段时间我的 chrome 扩展程序的 background.js 页面就会卡住,我不知道是什么原因造成的。

background.js 文件卡住时,它不再响应来自内容脚本的消息,当我尝试通过扩展管理器打开后台页面进行检查时,弹出窗口up 但一直是空白,没有界面出现。

我在后台页面中所做的唯一事情就是消息传递和检索本地存储变量。

我不知道是什么原因造成的,这个错误似乎只是在我从 chrome.extension api 过渡到新的 chrome.runtime api 后才发生的

谁能告诉我这里出了什么问题?或者帮我弄清楚?谢谢!

这是background.js文件的完整代码

if (!chrome.runtime) {
// Chrome 20-21
chrome.runtime = chrome.extension;
} else if(!chrome.runtime.onMessage) {
// Chrome 22-25
chrome.runtime.onMessage = chrome.extension.onMessage;
chrome.runtime.sendMessage = chrome.extension.sendMessage;

}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]}); // decodeURIComponent
else if (request.method == "setLocalStorage")
sendResponse({data: localStorage[request.key]=request.value});
else
sendResponse({}); // send empty response
});

是否可能发生卡住页面的死锁情况?它不会导致 CPU 发疯,所以我猜它不是无限循环。

更新这是请求的 manifest.json

{
"manifest_version": 2,
"content_scripts": [ {
"exclude_globs": [ "http://*.facebook.com/ajax/*", "https://*.facebook.com/ajax/*" , "http://www.facebook.com/ai.php?*", "https://www.facebook.com/ai.php?*", "http://www.facebook.com/ajax/*", "https://www.facebook.com/ajax/*"],
"include_globs": [ "http://*.facebook.com/*", "https://*.facebook.com/*" ],
"js": [ "script.js" ],
"matches": [ "http://*.facebook.com/*", "https://*.facebook.com/*" ],
"run_at": "document_start"
} ],
"converted_from_user_script": true,
"background": {"scripts": ["background.js"],
"persistent": false},
"icons": {
"128": "ET-128x128.png",
"48": "ET-48x48.png"
},
"key": "xxxxxxxxxxxxxxxxxxxx",
"name": "Extension Test",
"short_name": "ET",
"description": "ET Does this and that, but doesnt phone home",
"version": "999",
"homepage_url": "http://www.etphonehome.com"
}

一旦后台页面卡住,只有禁用并重新启用该扩展程序才能使其重新开始工作

下面是卡住后台页面检查窗口的截图: here is a screenshot of the frozen background page inspection window

最佳答案

localStorage API 是有问题的,因为在 chrome 中,它是一个同步 API,用于固有的异步操作(从渲染器进程调用,然后必须与浏览器进程通信,浏览器进程读取/写入文件系统中的后备存储,并且可能回复渲染器进程)。虽然理论上不应该导致网页或扩展代码死锁,但 chrome 的实现中可能存在错误。

您可能会尝试的一件事是从 localStorage 切换到 chrome.storage.local .由于它有一个异步 API,因此使用起来要多一些工作,但不会像 localStorage 那样具有相同的实现复杂性。

例如

sendResponse({data: localStorage[request.key]});

成为

chrome.storage.local.get(request.key, function(storageResult) {
sendResponse(storageResult[request.key]);
});

关于javascript - 是什么导致我的 chrome 扩展程序的 background.js 卡住并且不响应消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21740823/

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