繁体   English   中英

来自不同域的Greasemonkey AJAX请求?

[英]Greasemonkey AJAX request from a different domain?

我正在尝试使用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(和Tampermonkey)内置了对跨域AJAX的支持。 使用GM_xmlhttpRequest函数

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

// ==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) + '...'
                    );
                }
} );

你也应该养成使用@connect指令的习惯 - 尽管对于Firefox上的Greasemonkey并不是严格要求的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM