[英]Chrome Extension - how do I capture all runtime exceptions
I'm working on a Chrome extension which has a background script (or event script ) which runs continuously and detects if certain web pages are visited in any tab and then does some processing. 我正在使用一个具有后台脚本 (或事件脚本 )的Chrome扩展程序,该脚本可以连续运行并检测是否在任何选项卡中访问了某些网页,然后进行了一些处理。
I noticed that the script randomly stops working every now and then, but starts again if I restart the browser or inspect the console for the background script. 我注意到该脚本偶尔会不时地停止工作,但是如果我重新启动浏览器或检查控制台中的后台脚本,它将再次启动。
I know how to store data in chrome.storage.local and I want to be able to detect and make an entry everytime a runtime error is thrown, is this possible? 我知道如何将数据存储在chrome.storage.local中,并且我希望能够在每次引发运行时错误时进行检测并进行输入,这可能吗? ie a script wide catch block?
即一个脚本范围的捕获块?
I saw this post which explains how to handle runtime errors, but this only works within a single callback function. 我看到了这篇文章 ,其中解释了如何处理运行时错误,但这仅在单个回调函数中有效。 I want to be able to do this for the whole script.
我希望能够针对整个脚本执行此操作。
You are probably hitting the idle unload that Event pages use (since you say inspecting works - that wakes it up). 您可能正在使用事件页面使用的空闲卸载(因为您说正在检查工作-唤醒它)。
It was your choice to put in "persistent": false
and it comes with consequences . 选择
"persistent": false
是您的选择"persistent": false
,并带来后果 。
If you rely on any state variables, they will be lost when the page is unloaded. 如果您依赖任何状态变量,则在页面卸载时它们将丢失。 If you must keep any state at all, do it in
chrome.storage.local
. 如果您必须保留任何状态,请在
chrome.storage.local
。
Another common mistake is not re-registering all event listeners every time the script runs. 另一个常见的错误是没有在每次脚本运行时都重新注册所有事件侦听器。 The unload-but-remember-listeners mechanism depends on it;
卸载但记住侦听器机制依赖于此。 if an event is triggered, the following happens:
如果触发事件,则会发生以下情况:
So if you, say, registered a listener in a codepath that's not executed every time you run the script (eg not in a top-level statement but conditionally or asynchronously), then after waking up the script won't have that listener enabled and the event will be dropped: 因此,例如,如果您在并非每次运行脚本时都未执行的代码路径中注册了侦听器(例如,不在顶级语句中,而是有条件或异步地执行),则在唤醒脚本后,将不会启用该侦听器,并且该事件将被丢弃:
/* Chrome wakes up your page */
chrome.storage.local.get("option", function(data) {
if(data.option) {
// Asynchronous
chrome.someAPI.onSomeEvent.addListener(function() {
// This will not be handled after unload
});
}
});
// Synchronous
chrome.someAPI.onSomeEvent.addListener(function() {
// This will be handled after unload
chrome.storage.local.get("option", function(data) {
if(data.option) {
// Do stuff
});
}
});
/* At this point, Chrome triggers the event,
and if there are no listeners (re)registered it's lost */
So put any conditional/async processing inside the listeners. 因此,将所有条件/异步处理放入侦听器中。
There are also other reasons why it can stop working, but it's impossible to tell without seeing your code. 还有其他原因使其无法正常工作,但是如果不看代码就无法分辨。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.