这是我的GM_xmlhttpRequest脚本:
// ==UserScript==
// @name test
// @namespace test
// @include http://stackoverflow.com/*
// @version 1
// ==/UserScript==
GM_xmlhttpRequest({
method: "GET",
url: "http://example.com",
onload: function(response) {
alert(response.responseText);
}
});
function begin(){
alert("ready");
}
$(document).ready(function() {
begin();
});
仅提醒 example.com 的内容,而不是“就绪”。
但是当我执行以下操作时,什么也没有发生 - 没有任何警报:
function begin(){
GM_xmlhttpRequest({
method: "GET",
url: "http://example.com",
onload: function(response) {
alert(response.responseText);
}
});
alert("ready");
}
$(document).ready(function() {
begin();
});
我做错了什么?
最佳答案
我很确定第一个示例显示了 GM_xmlhttpRequest 返回的内容,但不是“ready”
jQuery/$ 无法在 Greasemonkey 中直接访问。它被加载到页面内(在本例中是由 stackoverflow.com 加载)。要访问页面的功能/属性,您可以使用 unsafeWindow-object( http://wiki.greasespot.net/UnsafeWindow ):
unsafeWindow.$(document).ready(function() {
begin();
});
但我建议直接调用 begin() ,这里不需要 $.ready()
,因为 GM 脚本将始终在 DOMContentLoaded-event 触发时执行,这是相等的到 $.ready()
关于javascript - 从 $(document).ready() 内部调用时 GM_xmlhttpRequest 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14120470/