/*** 这是GreaseMonkey脚本的自动升级辅助用代码。详见http://npchen.blogspot.com/2008/12/greasemonkey.html ***/ Function.prototype.bind = function(object){ var __method=this; return function(){__method.apply(object,arguments);} }; function CGM_getValue(v, utf8_defaultV) { var t = GM_getValue(v); if (t==undefined) return utf8_defaultV; else return decodeURIComponent(t); } function CGM_setValue(n, v) { GM_setValue(n, encodeURIComponent(v)); } var Updater = function (script) { this.script = script; this.key = 'update_lastChecked'; //GM_setValue前面会自动添加namespace和script name, key可用常量 this.lastCheck = CGM_getValue(this.key, 0); this.dateTime = Date.now()/1000; this.hoursToCheck = 10; GM_registerMenuCommand("\u66F4\u65B0"+this.script.name+"\u811A\u672C", this.update.bind(this)); } //用这个方法修改默认的检查频率 Updater.prototype.setHoursToCheck = function(t){ this.hoursToCheck = t; }; Updater.prototype.getVersion = function(meta){ var ver = meta.match(/\/\/\s*@version\s*(\d.*)/); return (ver===null) ? '0' : ver[1]; }; Updater.prototype.getReason = function(meta){ var reason = meta.substring(meta.search(/\/\*\s*@reason/im)); reason = reason.substring(0, reason.search(/@end\s*\*\//im)); reason = reason.replace(/\/\*\s*@reason/, ""); return reason; }; Updater.prototype.versionCompare = function(v1, v2){ var a1 = v1.split('.'); var a2 = v2.split('.'); do { var t1 = Number(a1.shift()); var t2 = Number(a2.shift()); if (t1 == t2) continue; return (t1>t2) } while((a1.length>0) && (a2.length>0)) return (a1.length>0) }; Updater.prototype.update = function( ){ this.meta_js = "http://userscripts.org/scripts/source/"+this.script.id+".meta.js"; this.user_js = "http://userscripts.org/scripts/source/"+this.script.id+".user.js"; GM_xmlhttpRequest({ method: 'GET', url: this.meta_js, onreadystatechange: this.process.bind(this) }); }; Updater.prototype.process = function(response){ this.result=false; CGM_setValue(this.key, this.dateTime); if ((response.readyState == 4) && (response.status == 200)) { var ver = this.getVersion(response.responseText); var reason = this.getReason(response.responseText); if (this.versionCompare(ver, this.script.version)){ alert(this.script.name+'\u66F4\u65B0\u81F3\u7248\u672Cv.'+ver+'\n\n'+reason); //更新至版本 this.result=true; window.status=this.script.name+'\u811A\u672C\u6709\u66F4\u65B0'; //脚本有更新 window.location.href = this.user_js; } } if (!this.result) window.status=this.script.name+'\u811A\u672C\u6CA1\u6709\u66F4\u65B0'; } Updater.prototype.check = function( ){ var dateDiff = this.dateTime - this.lastCheck; if ((dateDiff > (3600*this.hoursToCheck) ) || (dateDiff < 0)) { //每隔hoursToCheck检查一次. 默认是10小时 this.update(); } };