views:

2036

answers:

3

I'm trying to perform and AJAX query from within a grease monkey 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 fails with no error or alert on any other domain. Any suggestions?

+1  A: 

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

geowa4
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
+4  A: 

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

Photodeus
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
A: 

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

I have used in a sample application (see url below) 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.

http://sites.google.com/site/spyderhoodcommunity/tech-stuff/jqueryloadurldatafunc

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.

Kartik Sehgal