2008年11月10日 星期一

GM_xmlhttpRequest 和 unsafeWindow 的限制

詳細的限制請參考 http://wiki.greasespot.net/0.7.20080121.0_compatibility 的描述。主要的症狀是你會發現錯誤訊息出現:
Greasemonkey access violation: unsafeWindow cannot call GM_xmlhttpRequest. 

解決方法如下:

unsafeWindow.someObject.registerCallback(function(asin) {
  window.setTimeout(function() {  // 重點是利用 window.setTimeout
    GM_xmlhttpRequest({
       method: "GET",
       url: "http://www.amazon.com/asin/" + asin;
    });
  }, 0);    // <<<
});

實際例子

$("span[name!=NOT_AVAILABLE]").click(function(){
  GM_openInTab(entrezGene+$(this).attr("name"),1);
}).mouseover(function(){
  var url=url+$(this).attr("name")+".htm";
  window.setTimeout(function(ref){
    GM_xmlhttpRequest({
      method: "GET",
      url: url+"",
      onload: 
      function(xhr) {
 ref.attr("title","Information from Entrez Gene|"+xhr.responseText).cluetip(
 {width:400,splitTitle: '|',arrows: true,dropShadow: false, cluetipClass: 'gene', waitImage: true}
        );
      }
    });
  },0,$(this));  // 用這種方法可以將 $(this) 傳進去
});

沒有留言: