Chrome中的用户脚本,跨域通信

5

Chrome有自己的Greasemonkey,但它有许多限制。其中一个限制是它的xmlhttprequest不支持跨域。那么有没有办法让它工作呢?

谢谢。

2个回答

4

1

如果您想让脚本也能在Opera上运行,您仍然无法使用GM_xmlhttpRequest。但是,使用YQL和jQuery,您可以像这样实现:

var getCrossDomain = function (url, callback, maxage) {
        if (typeof (url) !== 'undefined') {
            var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + url + '"') + '&diagnostics=false&format=xml&callback=?&_maxage=';
            if (typeof (maxage) === 'undefined') {
                yql += '10000'; // Value is in ms
            }
            $.getJSON(yql, function (data) {
                if (typeof (callbackX) === 'function') {
                    callback(data.results[0]);
                }
            }).fail(function (jqXHR, textStatus, errorThrown) {
                // Some code here to handle a failed request
            });
        }
    };

阅读http://www.yqlblog.net/blog/2010/03/12/avoiding-rate-limits-and-getting-banned-in-yql-and-pipes-caching-is-your-friend/以获取有关maxage参数的信息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接