Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从$(document).ready()内部调用时,GM_xmlhttpRequest不起作用?_Javascript_Ajax_Greasemonkey_Gm Xmlhttprequest - Fatal编程技术网

Javascript 从$(document).ready()内部调用时,GM_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

这是我的GM\u 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对象():


但是我建议直接调用begin(),这里不需要
$.ready()
,因为当触发DOMContentLoaded事件时,GM脚本将始终执行,这等于
$.ready()

您是对的,第一个示例没有打印“ready”。我的错。我在两个警报之间进行测试,可能想象两个警报都出现了!只要调用begin()就行了。谢谢刚刚意识到脚本描述符中有/@grant none会阻止GM_xmlhttpRequest执行。
unsafeWindow.$(document).ready(function() {
    begin();
});