【问题标题】:Greasemonkey AJAX request from a different domain?来自不同域的 Greasemonkey AJAX 请求?
【发布时间】:2017-07-24 08:00:41
【问题描述】:

我正在尝试使用 JavaScript(使用 Greasemonkey)从我自己的站点中提取数据以自定义另一个站点。我使用的代码如下:

function getURL(url, func)
{
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.onload = function (e) 
  {
    if (xhr.readyState == 4) 
    {
      if (xhr.status == 200) 
      {
        func(xhr.responseText, url);
      } 
      else
      {
        alert(xhr.statusText, 0);
      }
    }
  };
  xhr.onerror = function (e)
  {
    alert("getURL Error: "+ xhr.statusText); // picks up error here
  };
  xhr.send(null);  
}

上面的工作非常好,它从 URL 中获取文本并将其返回给我传递给函数的匿名函数,只要该文件与我从中调用它的页面位于同一域中。但是,如果域不同,则会触发 onerror

我怎样才能把它整理出来,以便我可以从这个设置中的不同域中提取数据?

【问题讨论】:

  • 是您在greasemonkey 脚本中发布的代码吗?如果是这样,您需要使用greasemonkeys XHR - wiki.greasespot.net/GM_xmlhttpRequest
  • 旁注:您可能应该考虑将您的代码移植到web extension - 因为我认为greasemonkey 不会在Firefox 57 中存活 - 开发人员并不热衷于将greasemonkey 移植到Web 扩展- 他们在最近的e10s 兼容性方面遇到了很多问题,我认为 10 年后,他们已经受够了:p
  • @JaromandaX,即使 当前 领导开发者丢球(更多/再次),其他人无疑会捡起它。 Firefox 上的 Tampermonkey 也是一个越来越可行的选择。
  • 当然! Tampermonkey - 感谢@BrockAdams 的提醒
  • 谢谢大家,这是一个帮助。实际上,由于我控制了域,因此我可以通过在页面上使用不同的 CORS 标头编辑发送的数据来解决问题。有人提到过,但把它删掉了。尽管如此,在我不控制数据的情况下,了解 GM 扩展仍然非常方便。 spring.io/understanding/CORS

标签: javascript ajax http greasemonkey tampermonkey


【解决方案1】:

Greasemonkey(和 Tampermonkey)内置了对跨域 AJAX 的支持。使用the GM_xmlhttpRequest function

这是一个完整的用户脚本,说明了这个过程:

// ==UserScript==
// @name        _Starter AJAX request in GM, TM, etc.
// @match       *://YOUR_SERVER.COM/YOUR_PATH/*
// @grant       GM_xmlhttpRequest
// @connect     targetdomain1.com
// ==/UserScript==

GM_xmlhttpRequest ( {
    method:     'GET',
    url:        'http://targetdomain1.com/some_page.htm',
    onload:     function (responseDetails) {
                    // DO ALL RESPONSE PROCESSING HERE...
                    console.log (
                        "GM_xmlhttpRequest() response is:\n",
                        responseDetails.responseText.substring (0, 80) + '...'
                    );
                }
} );

您还应该养成使用the @connect directive 的习惯——尽管对于 Firefox 上的 Greasemonkey 并不是严格要求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-08
    • 2010-09-24
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2013-04-16
    相关资源
    最近更新 更多