简体   繁体   English

页面刷新后,Chrome API警报停止

[英]Chrome API Alarm stops after page refresh

Reading around, I was under the impression that the Chrome alarm continues to work even after Chrome is closed, page refreshed etc. From one of the Google results: 环顾四周,我给人的印象是,即使关闭了Chrome,刷新了页面等,Chrome警报仍然可以继续工作。来自Google的结果之一:

With the Chrome alarm APIs, you can set an alarm that lasts as long as the app is installed, even if its background page goes inactive. 使用Chrome警报API,即使应用程序的后台页面处于非活动状态,您也可以设置持续到安装该应用程序的警报。

My problem is that I have setup a Chrome alarm in my options.js page for a Chrome Extension. 我的问题是我在options.js页面中为Chrome扩展程序设置了Chrome警报。 The alarm is created (chrome.alarms.create) when the options page is saved. 保存选项页面后,便会创建警报(chrome.alarms.create)。

The alarm works if I keep my page open. 如果我保持页面打开,则警报有效。 However, if I reload the page (options.html), I don't get the alarms anymore. 但是,如果我重新加载页面(options.html),则不会再收到警报。

Here is part of my options.js 这是我的options.js的一部分

$('#save-options-button').on('click', function() {

    //Clears existing alarm
    chrome.alarms.clearAll();

    //Create alarm
    chrome.alarms.create("fetchAlarm", {
        delayInMinutes: 1,
        periodInMinutes: 1
    });

    chrome.alarms.onAlarm.addListener(function(alarm) {
        console.log("Got an alarm!", alarm);

    });
});

I guess you are quoting the Chrome Apps documentation, that's why it gets confusing. 我猜您是在引用Chrome Apps文档,这就是为什么它会引起混淆。

What was meant is that event pages (a type of background page ) will be woken up to serve an alarm event even if they were unloaded for being idle. 这意味着事件页面 (一种背景页面 )将被唤醒以提供警报事件,即使它们是由于空闲而卸载的。

This applies only to event/background pages. 适用于事件/背景的网页。 Chrome would not randomly open a page only because an event that the page listened to in the past happened. Chrome浏览器不会仅仅因为页面过去监听的事件发生而随机打开页面。 As such, you should not put actual event listener logic into UI pages (options, popup, etc.) 因此,您不应将实际的事件侦听器逻辑放入UI页面(选项,弹出窗口等)中。

In your case, refreshing the page makes the JS context that contained the listener to be destroyed along with it, and your logic only adds a listener after a click. 在您的情况下,刷新页面会使包含侦听器的JS上下文与其一起被销毁,并且您的逻辑仅在单击后添加一个侦听器。 Even if you added that addListener to the top level code instead, it would only function as long as the page is open. 即使将addListener到顶级代码中,它也仅在打开页面后才起作用。

So, you will need to add a background page to service that event (the actual listener). 因此,您将需要添加一个后台页面来服务该事件(实际的侦听器)。

A background page is normally always ready to answer events. 后台页面通常总是准备好回答事件。 Event pages are special in that Chrome remembers which events should trigger their load and doesn't keep them loaded. 事件页面的特殊之处在于,Chrome会记住哪些事件应触发其加载,而不会保持加载。 You can read more about it in another answer of mine . 您可以在我的另一个答案中了解更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM