如何在Firefox中允许来自greasemonkey脚本的跨源请求? [英] How do I allow Cross-Origin Requests from greasemonkey scripts in Firefox?
问题描述
我正在开发一个Greasemonkey脚本,在网页上实现了一些工具。这个脚本从
http://localhost/chess/heartbeat.php
$ b现在在Firefox中,我得到了这个控制台错误,它完全停止了我的jQuery AJAX数据请求。
跨源请求被阻止:同源策略不允许在
处读取远程资源HTTP://localhost/chess/heartbeat.php。
这可以通过将资源移动到相同的域或启用CORS。
我可以使用Google Chrome解决此问题。当我把它作为chrome的一个简单的浏览器扩展时,我可以使它与Greasemonkey做同样的事情,我可以添加下面的权限到插件的清单文件,它允许我做出相同的数据请求,Firefox阻止:
permissions:[
,其中包括jQuery的更高级别的API,不允许不受限制的跨站点请求,但受限于同源策略和 CORS 。
< all_urls>
$ b无论如何,这个工作在chrome上,但我想达到同样的效果Firefox浏览器。我一直在研究这个问题,我找不到一个简单的答案。通常
XMLHttpRquest
正如@epascarello已经指出的那样,您可以使用
GM_xmlhttpRequest
( Scriptish ),即使服务器没有实现CORS或者允许源站点,它也允许你执行任何跨站点的XHR。它还带有一些其他的好东西。
您应该添加一个
@grant GM_xmlhttpRequest
元数据块添加到您的用户脚本中,否则您的脚本可能会在未来中断。
提到的Chrome扩展:Firefox扩展也可以执行跨站点XHR。
E.g.大多数用户脚本应该可以使用PageMod
并启用某些权限与您在Chrome扩展程序中所做的相似。I'm developing a Greasemonkey script that implements a couple of tools onto a webpage. This script makes a request for data from
http://localhost/chess/heartbeat.php
Now currently in Firefox I am getting this console error which totally stops my jQuery AJAX request for data.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at
http://localhost/chess/heartbeat.php.
This can be fixed by moving the resource to the same domain or enabling CORS.
I am able to work around this using Google Chrome. When I have it as a simple browser extension for chrome, I'm able to have it do the same thing as Greasemonkey and I can add the following permissions to the manifest file for the plugin which allows me to make the same data request which Firefox blocked:
"permissions": [ "<all_urls>" ]
Anyway, this works on chrome, but I want to achieve the same effect on Firefox. I've been researching this issue and I can't find a simple answer.
解决方案Normally
XMLHttpRquest
, and that includes jQuery's higher-level API around it, does not allow unrestricted cross-site requests but is limited by the same-origin policy and CORS.As @epascarello already pointed out, you may use
GM_xmlhttpRequest
(Scriptish) which allows you to perform any cross-site XHR even when the server does not implement CORS or allows the origin site. It also comes with some other goodies.You should add a
@grant GM_xmlhttpRequest
meta data block to your user script, or your script may break in the future.Since you mentioned Chrome extensions: Firefox extensions can perform cross-site XHR as well. E.g. most user scripts should be easily portable to an SDK add-on using
PageMod
and enabling certain permissions analog to what you'd do in a Chrome extension.这篇关于如何在Firefox中允许来自greasemonkey脚本的跨源请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!