Javascript 从$(document).ready()内部调用时,GM_xmlhttpRequest不起作用?
这是我的GM\u xmlhttpRequest脚本:Javascript 从$(document).ready()内部调用时,GM_xmlhttpRequest不起作用?,javascript,ajax,greasemonkey,gm-xmlhttprequest,Javascript,Ajax,Greasemonkey,Gm Xmlhttprequest,这是我的GM\u xmlhttpRequest脚本: // ==UserScript== // @name test // @namespace test // @include http://stackoverflow.com/* // @version 1 // ==/UserScript== GM_xmlhttpRequest({ method: "GET", url: "http://example.com", onload: functi
// ==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对象():
但是我建议直接调用begin(),这里不需要
$.ready()
,因为当触发DOMContentLoaded事件时,GM脚本将始终执行,这等于$.ready()
您是对的,第一个示例没有打印“ready”。我的错。我在两个警报之间进行测试,可能想象两个警报都出现了!只要调用begin()就行了。谢谢刚刚意识到脚本描述符中有/@grant none会阻止GM_xmlhttpRequest执行。
unsafeWindow.$(document).ready(function() {
begin();
});