问题
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?
回答1:
Only GM_xmlhttpRequest can do cross-site access, not the normal XMLHttpRequest that jQuery uses.
回答2:
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
回答3:
Yeah, you can't do that. It's called XSS
回答4:
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.
来源:https://stackoverflow.com/questions/728138/load-remote-url-with-greasemonkey-and-jquery