简体   繁体   中英

setTimeOut scope in a Chrome extension

I have a notification functionality in my chrome extension which is managed by a background page (background.html) This page calls the setNotificationDelay() function which is basically a deletion of the previous timer followed by a setTimeOut.

function setNotificationDelay() {
    clearNotificationTimer();
    newDelay = getNotificationDelay()
    notificationTimer = setTimeout(showNotification, newDelay);
    }
}

I have also an options.html page which allows the configuration of the notification hour. I want to modify the background timeout when the configuration is modified, but when I call the setNotificationDelay() from the Option page it doesn't work, and I presume it's because the scope of the timers are attached to the parent page.

If I let the Option page opens the timeout is triggered, if I close it the notification never happened.

How can I attach this timer to the background page ? Is there a better way to achieve it ?

Thanks.

EDIT: The chrome.extension have the getBackground page method which returns the window object for the background page:

function setNotificationDelay() {
    clearNotificationTimer();
    newDelay = getNotificationDelay()
    notificationTimer = chrome.extension.getBackgroundPage().setTimeout(showNotification, newDelay);
    }
}

options.js is only active while the options.html page is open, and I presume you don't want to leave the page open while you're waiting for the notification. What you want (I think) is to have background.js set the notification (both background.js and options.js access the same string variable localStorage.yourNotificationDelay ).

One thing to watch out for is that if you are using event pages instead of background pages, a notification of more than a few seconds won't happen because Chrome will unload the background page. In that case, you'll need to use alarms instead.

Edit: Your edit makes me think I'm not understanding you. Perhaps you're expecting the user to change the interval while the timer is running? Then I'd recommend sending a message to background.js with newDelay , and use that to call setNotificationDelay() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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