Greasemonkey AJAX request from another domain?

I am trying to get JavaScript (using Greasemonkey) to retrieve data from my own site in order to set up another site. The code I use 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 fine, it gets the text from the URL and returns it to an anonymous function, which I pass to the function if the file is in the same domain as the page I'm calling from. However, if the domain is different, then it works onerror.

How can I sort it so that I can retrieve data from another domain in this setting?

+4
source share
1 answer

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 - Greasemonkey Firefox, .

+5

Source: https://habr.com/ru/post/1671429/


All Articles