1

I'm trying to perform an Ajax query from within a Greasemonkey script, but I'm stuck with not being able to load data from a remote URL. The script only seems to function if the page being viewed is the same domain as the Ajax call. Example:

// ==UserScript==
// @name          Hello jQuery
// @namespace     http://www.example.com/
// @description   jQuery test script
// @include       *
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js
// ==/UserScript==

$(document).ready(function() {
    $.get("http://www.google.com", function(data){
        alert("Data Loaded: " + data);
    });
});

// EOF

This user script works perfectly when visiting google.com, but it fails with no error or alert on any other domain. What is the solution?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

4 Answers4

4

Only GM_xmlhttpRequest can do cross-site access, not the normal XMLHttpRequest that jQuery uses.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Photodeus
  • 657
  • 1
  • 5
  • 18
  • But you can still take the responseText and feed it into jQuery if you want to use the usual stuff to parse it: $(responseText) – Plutor May 07 '09 at 17:08
0

In Greasemonkey, there is a function called GM_xmlhttpRequest for XMLHttpRequest. However, it does not comply with the XmlHttprequest interface. Hence, it is not possible to use it with jQuery. This works with jQuery 1.5.

jQuery Ajax in Greasemonley then looks like:

$.ajax({
    url: '/p/',// this even works for cross-domain requests by default
    xhr: function(){ return new GM_XHR(); },
    type: 'POST',
    success: function(val){
        ...
    }
});

Source: http://www.monperrus.net/martin/greasemonkey+jquery+and+xmlhttprequest+together

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Faron
  • 9
  • 2
-1

Yeah, you can't do that. It's called XSS

geowa4
  • 40,390
  • 17
  • 88
  • 107
  • 3
    Greasemonkey's version of XHR, [GM_xmlhttpRequest](http://wiki.greasespot.net/GM_xmlhttpRequest) is not subject to the same origin policy that prevents XSS. – Ryan Mar 24 '10 at 00:05
-1

You can try load(URL, [data], [func]).

I have used it in a sample application, and it loaded Google search for me even though it is on another domain. There is a downside, that a JavaScript security alert will come when you try to access another domain.

I hope it helps!

P.S. I actually tried a non-Google domain and received some errors. But I found, the error was there because the page was not compatible with the response content being received (JavaScript errors, etc). I did find some pages execute successfully, that I created in another domain. So you have to watch out for what kind of content also you load.

Probably, in such a case, loading the content in an iframe would be better for you.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kartik Sehgal
  • 143
  • 2
  • 8