简体   繁体   中英

Greasemonkey AJAX request from a different domain?

I'm trying to get JavaScript (with Greasemonkey) to pull data from my own site to customize another site. The code I'm using is as follows:

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);  
}

The above works perfectly fine, it gets the text from the URL and returns it to the anonymous function that I pass into the function, as long as the file is on the same domain as the page I'm calling it from. However, if the domain is different then the onerror gets triggered.

How can I sort it out so I can pull in data from a different domain in this set up?

Greasemonkey (and Tampermonkey) has built-in support for cross-domain AJAX. Use the GM_xmlhttpRequest function .

Here's a complete userscript that illustrates the process:

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

You should also get in the habit of using the @connect directive -- even though it's not strictly required for Greasemonkey on Firefox, yet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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