Chrome Extension - Use javascript to run periodically, and log data permanently

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.

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.

Answers:

Answer

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.

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
            });
        }
    });
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.