Reputation: 704
I am trying to add some code to a chrome extension, that will refresh a specific page at a certain time of the day. I've found coding that involves adding meta tags to the header, or tags to the body but I cant edit the page's html so this is not possible. This is the code I have of now but it doesnt seem to be working --
//60000 milliseconds is 1 minute
window.setInterval("checkForRefresh()", 60000);
function checkForRefresh() {
var now = new Date();
if (now.getHours() == 14 && now.getMinutes() == 24) {
window.location.reload();
}
}
It seems to have worked a couple of times, but now it just stopped working. Not sure what went wrong.
Any ideas on how to fix this?
Upvotes: 0
Views: 6094
Reputation: 48211
For a more reliable and resource friendly solution, you could use the chrome.alarms
API in a non-persistent background page (a.k.a. event page). E.g.:
In manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"offline_enabled": false,
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"permissions": [
"alarms",
"tabs"
]
}
In background.js:
var refreshAlarmName = 'refreshAlarm';
/* Refresh at: 10 Dec 2013, 22:11:00 UTC */
var utcYear = 2013;
var utcMonth = 11; // <-- watch out: this is zero-based
var utcDate = 10;
var utcHours = 22;
var utcMinutes = 11;
/* Convert a date (year, month, dayOfMonth, hours, mins)
* to milliseconds past the epoch */
function at(year, month, dayOfMonth, hours, mins) {
var date = new Date();
date.setUTCFullYear(year);
date.setUTCMonth(month);
date.setUTCDate(dayOfMonth);
date.setUTCHours(hours);
date.setUTCMinutes(mins);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
return date.getTime();
}
chrome.alarms.create(refreshAlarmName, {
when: at(utcYear, utcMonth, utcDate, utcHours, utcMinutes)
});
chrome.alarms.onAlarm.addListener(function(alarm) {
if (alarm.name !== refreshAlarmName) {
return;
}
chrome.tabs.query({ url: "*://www.eastbay.com/*" }, function(tabs) {
tabs.forEach(function(tab) {
chrome.tabs.reload(tab.id, { bypassCache: true });
});
});
});
According to the docs:
For performance reasons, the alarm may have been delayed an arbitrary amount beyond this.
According to my experience, that arbitrary amount is hardly ever more than negligible, but if the exact timing is of the essence, you might want to consider a more sophisticated mechanism, where the background page fire's an alarm a couple of minutes before the target time, which injects a content script that sets a, say, 30secs interval to check for the target time and refresh.
Upvotes: 0
Reputation: 113
Use location.reload(true)
That'll reload the page and bypass the cache, however, if you don't want to bypass the cache, set then use location.reload(false)
Take a look at this.
Upvotes: 3
Reputation: 5589
window.refresh()
is not a function. Try window.location.reload()
instead.
Upvotes: 1