Cross-origin XHR from a user script in Google Chrome

纵饮孤独 提交于 2019-11-27 04:37:44

问题


Has anybody had any luck performing cross origin XHRs from a user script in Google Chrome? The requests go through to the server (I can see them in the logs) but, the readystatechanged event is never fired.

Extension permissions don't seem to be doing the trick. Neither is JSONP.


回答1:


Current versions of Chrome (13.0.781 or later) now support most or all of the GM_xmlhttpRequest()Doc functionality -- including cross-domain requests.
See Issue 18857: Support cross-site XMLHttpRequest in content scripts.

So this script works perfectly fine now on Chrome (and Firefox, of course):

// ==UserScript==
// @name            _Cross domain (XSS) GM_xmlhttpRequest, Chrome too
// @include         http://stackoverflow.com/*
// @grant           GM_xmlhttpRequest
// ==/UserScript==

GM_xmlhttpRequest ( {
    method:     "GET",
    url:        "http://www.google.com/",
    onload:     function (response) {
                    console.log (   response.status,
                                    response.responseText.substring (0, 80)
                                );
                }
} );


(Install that script, then browse any SO page. The script will write the first 80 characters of the Google home page to the console.)




回答2:


As of Chrome 13, you can do cross origin requests in Content Scripts if you included the permission to the website in the manifest.

A user script in Chrome is a content script. Content scripts cannot make cross-origin XHRs. If you wish to do cross-origin XHRs, it should be done in the extension pages (background, popup, options).

For more info: http://code.google.com/chrome/extensions/content_scripts.html http://code.google.com/chrome/extensions/xhr.html



来源:https://stackoverflow.com/questions/1936639/cross-origin-xhr-from-a-user-script-in-google-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!