Chrome扩展程序 - 使用javascript定期运行,并永久记录数据

问题描述:

目前,我有一个脚本,当右上方托盘中的图像被点击(只针对一个特定的允许网站),它扫描页面HTML然后输出一些值。这种扫描和输出是单个JS文件中的一个函数,称为checkData.js。

Currently, I have a script that when the image in the top right tray is clicked(only for one specific allowed website), it scans the pages HTML then outputs some value. This scanning and outputting is a function in a single JS file, called say checkData.js.

这是可能的,即使用户没有使用标签页,是打开的,自动使脚本每10秒运行一次,并将数据记录到某个地方,我可以稍后在扩展中访问?这是因为页面HTML是不断变化的。

Is it possible, even if a user is not actively using a tab but it is open, to automatically have the script run every 10 seconds and log data to some place I can access later within the extension? THis is because the pages HTML is constantly changing. The I suppose I would use alarms or event pages, but I am not sure how to integrate that.

Chrome限制了频率的使用频率,因此我将使用闹钟或事件页面,但我不知道如何整合。每分钟至多重复一次报警。如果没关系,请按照下列步骤操作:

Chrome limits the frequency of repeating alarms to at most once per minute. If that is OK, here is how to do it:

请参阅这里如何设置活动页面。

See here on how to setup an event page.

在background.js中,您将执行以下操作:

In the background.js you would do something like this:

// event: called when extension is installed or updated or Chrome is updated
function onInstalled() {
    // CREATE ALARMS HERE
    ...
}

// event: called when Chrome first starts
function onStartup() {
    // CREATE ALARMS HERE
    ...
}

// event: alarm raised
function onAlarm(alarm) {
    switch (alarm.name) {
        case 'updatePhotos':
            // get the latest for the live photo streams
            photoSources.processDaily();
            break;
        ...
        default:
            break;
    }
}

// listen for extension install or update
chrome.runtime.onInstalled.addListener(onInstalled);

// listen for Chrome starting
chrome.runtime.onStartup.addListener(onStartup);

// listen for alarms
chrome.alarms.onAlarm.addListener(onAlarm);

创建重复的闹钟,如下所示:

Creating a repeating alarm is done like this:

// create a daily alarm to update live photostreams
function _updateRepeatingAlarms() {
    // Add daily alarm to update 500px and flickr photos
    chrome.alarms.get('updatePhotos', function(alarm) {
        if (!alarm) {
            chrome.alarms.create('updatePhotos', {
                when: Date.now() + MSEC_IN_DAY,
                periodInMinutes: MIN_IN_DAY
            });
        }
    });
}