Created
February 28, 2009 01:03
-
-
Save mislav/71807 to your computer and use it in GitHub Desktop.
generic update checker method for scripts on userscripts.org
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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