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.
Allow CORS: Access-Control-Allow-Origin lets you easily perform cross-domain Ajax requests in web applications. Simply activate the add-on and perform the request. CORS or Cross Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs).
Click on the Firefox drop-down menu at the top left of the browser and select Add-ons. Type Greasemonkey into the add-ons search box at the top right of the browser. Find Greasemonkey in the list and click on Install.
Greasemonkey is a userscript manager made available as a Mozilla Firefox extension.
In Java servlets. Simply add a header to your HttpServletResponse by calling addHeader : response. addHeader("Access-Control-Allow-Origin", "*");
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
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
metadata 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With