Skip to content

Instantly share code, notes, and snippets.

@mislav
Created February 28, 2009 01:03
Show Gist options
  • Save mislav/71807 to your computer and use it in GitHub Desktop.
Save mislav/71807 to your computer and use it in GitHub Desktop.
generic update checker method for scripts on userscripts.org
var checkUserscriptUpdate = (function(){
if (typeof GM_xmlhttpRequest != "function") return (function() {}) // no-op
var update = {
get available() { return getValue('updateAvailable', false) },
set available(value) { setValue('updateAvailable', value) },
get scriptLength() { return getValue('scriptLength') },
set scriptLength(value) { setValue('scriptLength', value) },
get checkedAt() { return getValue('updateTimestamp') },
set checkedAt(value) { setValue('updateTimestamp', value) },
interval: 172800 // 2 days
}
// detect user has updated script
if (update.scriptLength != scriptLength) {
update.available = false
update.scriptLength = scriptLength
}
function validateScriptLength(length, scriptLength) {
update.available = scriptLength != length
}
return function(scriptURL, scriptLength, callback) {
var sourceURL = scriptURL.replace(/show\/(\d+)$/, 'source/$1.user.js')
if (!update.available) {
var time = Math.floor(new Date().getTime() / 1000),
performCheck = time > update.checkedAt + update.interval
if (update.checkedAt && performCheck) {
GM_xmlhttpRequest({
url: sourceURL, method: 'HEAD',
headers: { 'Accept-Encoding': '' }, // no gzip, k thx bai
onload: function(r) {
var match = r.responseHeaders.match(/Content-Length: (\d+)/)
if (match) validateScriptLength(Number(match[1]), scriptLength)
log('Performed check for userscript update (result: %s)', update.available)
}
})
}
if (!update.checkedAt || performCheck) update.checkedAt = time
}
if (update.available) callback()
}
})()
/*** EXAMPLE USAGE ***/
var scriptURL = 'http://userscripts.org/scripts/show/24398'
checkUserscriptUpdate(scriptURL, 12345, function() {
// this will get run if an update is found,
// so insert some message for the user in the page
// with a link to `scriptURL`
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment