2013-01-10 37 views
2

我不能讓我的Greasemonkey腳本工作......Greasemonkey函數在我的腳本中不起作用?

GM_registerMenuCommand("What's My IP Address?", function(){ 

GM_xmlhttpRequest({ 
    method: "GET", 
    url: "http://tools.ip2location.com/ib2", 
    onerror: function(oEvent){ alert("Error " + oEvent.target.status + " occurred while receiving the document."); }, 
    onload: function(response){ 
     if (response.readyState !== 4 || response.status !== 200) return; 
     // we can parse now 
     var myregexp = /<a[^>]*>([\s\S]*?(?:Your IP Address)[\s\S]*?)<\/a>/i; 
     var match = myregexp.exec(response.responseText); 
     if (match != null) { 
      // got match 
      subject = match[1]; 
      // format first line 
      subject_2 = subject.replace(/<br><b>/mg, " "); 
      // remove html 
      subject_3 = subject_2.replace(/<\/?[a-z][a-z0-9]*[^<>]*>|<!--[\s\S]*?-->/ig, ""); 
      // now remove whitespaces 
      result = subject_3.replace(/^[ \s]*/mg, ""); 
     } else { 
      // no match, error 
      result = "I couldn't find your IP Address :("; 
     } 
     alert(result); 
    } 
}); 

}); 

(function(){ 

})(); 


沒有與GM_registerMenuCommand發生。

我可以拋出警報,讓我知道腳本正在運行,但是如何運行GM_registerMenuCommand

+0

你的腳本對我來說運行良好。它顯示我的IP/ISP /國家等在Firefox中的警報就好了。 –

+0

嗯,我不明白我在做什麼錯誤..你用它就像它是? – bushdiver

+0

只需添加一些元標記。已上傳到jsfiddle:http://jsfiddle.net/9Wp4D/ –

回答

8

從版本2.0開始,Greasemonkey現在默認爲@grant none

您必須明確地將@grant GM_xmlhttpRequest添加到userscript元數據塊,否則GM_xmlhttpRequest將不會提供給您的用戶腳本。

// ==UserScript== 
[...] 
// @grant GM_registerMenuCommand 
// @grant GM_xmlhttpRequest 
// ==/UserScript==