【问题标题】:GM_xmlhttpRequest does not work when called from inside $(document).ready()?从 $(document).ready() 内部调用 GM_xmlhttpRequest 不起作用?
【发布时间】:2013-01-02 10:31:37
【问题描述】:

这是我的 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();
}); 

我做错了什么?

【问题讨论】:

  • 刚刚意识到脚本描述符中有 // @grant none 会阻止 GM_xmlhttpRequest 执行。

标签: javascript ajax greasemonkey gm-xmlhttprequest


【解决方案1】:

我很确定第一个示例显示了 GM_xmlhttpRequest 返回的内容,而不是“ready

jQuery/$ 不能在 Greasemonkey 中直接访问。它在页面内加载(在本例中由 stackoverflow.com 加载)。要访问页面的功能/属性,您可以使用 unsafeWindow-object(http://wiki.greasespot.net/UnsafeWindow):

unsafeWindow.$(document).ready(function() {
    begin();
}); 

但我建议直接调用begin(),这里不需要$.ready(),因为当DOMContentLoaded-event触发时GM-scripts总是会执行,等于$.ready()

【讨论】:

  • 你是对的,第一个例子没有打印“准备好”。我的错。我在警报之间进行测试,也许想象两个警报都会出现!只需调用 begin() 即可。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多