SecurityError: The operation is insecure - window.history.pushState() - javascript

I'm getting this error in Firefox's Console: SecurityError: The operation is insecure and the guilty is HTML5 feature: window.history.pushState() when I try to load something with AJAX. It is supposed to load some data but Javascript stops executing on error.
I'm wondering why this may be happening. Is this some server misconfiguration? Any help would be appreciated.
UPDATE: Yes, it was a server error with domain name not matching: http://en.wikipedia.org/wiki/Same-origin_policy

Make sure you are following the Same Origin Policy. This means same domain, same subdomain, same protocol (http vs https) and same port.
How does pushState protect against potential content forgeries?
EDIT: As #robertc aptly pointed out in his comment, some browsers actually implement slightly different security policies when the origin is file:///. Not to mention you can encounter problems when testing locally with file:/// when the page expects it is running from a different origin (and so your pushState assumes production origin scenarios, not localhost scenarios)

We experienced the SecurityError: The operation is insecure when a user disabled their cookies prior to visiting our site, any subsequent XHR requests trying to use the session would obviously fail and cause this error.

In my case I was missing 'www.' from the url I was pushing. It must be exact match, if you're working on www.test.com, you must push to www.test.com and not test.com

You should try not open the file with a folder-explorer method (i.e. file://), but open that file from http:// (i.e. http://yoursite.com/ from http://localhost/)

I had this problem on ReactJS history push, turned out i was trying to open //link (with double slashes)

I had the same problem when called another javascript file from a file without putting javascript "physical" address.
I solved it by calling it same way from the html, example: "JS / archivo.js" instead of "archivo.js"

When creating a PWA, a service worker used on an non https server also generates this error.

replace serviceWorker.unregister() to serviceWorker.register() in index.js file

I solved it by switching tohttp protocol from the file protocol.
you can use "live-server" extension in VS code,
or, on node, use live-server [dirPath]

I had the same problem and it was caused by setting <base href=> to a naked domain while my server always served the www domain. Adding the www to the url in base href solved the issue.

Related

XMLHttpRequest cannot load - file footer.html, "Error: Failed to execute 'send' on 'XMLHttpRequest'

I have two of the same site. My 1st site is http://educationaboveall.org/ and the 2nd is http://www.savantgenius.com .
1st site is loading properly on every device without any error but the 2nd (www.savantgenius.com) site is not loading properly in mobile and table devices. It is only loading properly in desktop browser. I have also found 32 console error.
Are there any jQuery issues? And please tell me how to be able to fix it.
I'm getting the "XMLHttpRequest cannot load
file:///D:/Work%20File/My%20Work%20File/mY%20Work%20Backup/Sophie/Work%20File/footer.html.
Cross origin requests are only supported for HTTP." and "Error: Failed
to execute 'send' on 'XMLHttpRequest': Failed to load
'file:///D:/Work%20File/My%20Work%20File/mY%20Work%20Backup/Sophie/Work%20File/footer.html"
error, but I don't know what's causing it nor how to fix it.
Please see the screenshot - http://prntscr.com/4fm0d8
I Think that you should call it from a http webserver and not like simple file in browser. This mean request a file in a web server like http://localhost/XML/catalog.html not from file:///E:/Projects/XML/catalog.html.
It is as the message says:
cannot load file:///D:/Work%20File/My%20Work%20File/mY%20Work%20Backup/Sophie/Work%20File/footer.html. .
You are referencing to a file on a Windows boxes filesystem and not in a webservers folder.
Second: you have a CORS-issue (which in this case is caused by the filesystem reference)
Cross origin requests are only supported for HTTP
See MDN for more infos.
To solve the issue, you have to configure your webserver to allow such requests. Check your webservers manual.
I had the same problem with my InfluxDB connection and it turns out I did not prepend the URL settings in the datasource with 'http://'. This could be nicer in Grafana, e.g. mentioning there is no protocol defined for accessing the source.
In your case it's clear that you somehow configured Grafana to look for D:\, which is not accessible for your browser. So check your data source URL.

Text File to Var in Chrome - Javascript

Final product: take a file called theFile.txt which is saved with the js and HTML file and have it broken up by line into an array.
Problem: Works fine in Firefox but revives the following error in Google Chrome:
XMLHttpRequest cannot load file:///C:/Users/(my name)/Documents/testFile/theFile.txt. Received an invalid response. Origin 'null' is therefore not allowed access.
Javascript code:
$('#infoStore').load('theFile.txt', function(result) {
text = result;
console.log('here: '+text);});
HTML code for infoStore:
<div id="infoStore" hidden="true"></div>
Thank you in advance for your assistance. I will be online to answer questions often.
That's because Chrome treats all origins using the file: protocol as being different from each other, and so the Same Origin Policy comes into play. It's just a security choice distinction between Chrome and some other browsers.
You basically can't use ajax with local files served via the file: protocol. (In Chrome.)
You could read the file using the File API (this answer shows how), but of course that has limitations (not least that the user has to give you the file to read, either via <input type="file"> or drag and drop).
This happens because of Same-Origin-Policy. You should load that file from webserver, not from local directory.
If you want to access local file in chrome ??
Sometimes it’s cool to debug and test javascript applications in Chrome but you want to read / write to local files. Example: you’re looking to use ajax and do a $.getJSON(‘json/somefile.json’). Chrome by default won’t allow this and will throw an error similar to
Failed to load resource: No 'Access-Control-Allow-Origin'
header is present on the requested resource.
Origin 'null' is therefore not allowed access.
Or
XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin'
header is present on the requested resource.
Origin 'null' is therefore not allowed access.
Chrome does have a switch to enable this, it’s quite easy to turn on. You’ll need to make sure Chrome is closed completely, and run chrome with the ‘–allow-file-access-from-files’ flag. Ie:
C:\Users\<user>\AppData\Local\Google\Chrome\Application>
chrome --allow-file-access-from-files
Or you should be able to run:
%localappdata%\google\chrome\application\chrome --allow-file-access-from-files
I’ve made the below into a .bat file I use, if you find it helps.
start "chrome" %localappdata%\google\chrome\application\chrome --allow-file-access-from-files
exit
To see if the flag is set, you can visit: chrome://version/ and look at the Command Line section and you should see –allow-file-access-from-files
You’ll most likely need to run this with at least admin access, and I would caution visiting unknown sites with this setting on, as they could capitalize on your setting and potentially read local files.
REF: Reference Link -Allow Local File Access in Chrome (Windows)

Origin null is not allowed by Access-Control-Allow-Origin while trying to access a REMOTE XML file [duplicate]

I'm developing a page that pulls images from Flickr and Panoramio via jQuery's AJAX support.
The Flickr side is working fine, but when I try to $.get(url, callback) from Panoramio, I see an error in Chrome's console:
XMLHttpRequest cannot load http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=processImages&minx=-30&miny=0&maxx=0&maxy=150. Origin null is not allowed by Access-Control-Allow-Origin.
If I query that URL from a browser directly it works fine. What is going on, and can I get around this? Am I composing my query incorrectly, or is this something that Panoramio does to hinder what I'm trying to do?
Google didn't turn up any useful matches on the error message.
EDIT
Here's some sample code that shows the problem:
$().ready(function () {
var url = 'http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=processImages&minx=-30&miny=0&maxx=0&maxy=150';
$.get(url, function (jsonp) {
var processImages = function (data) {
alert('ok');
};
eval(jsonp);
});
});
You can run the example online.
EDIT 2
Thanks to Darin for his help with this. THE ABOVE CODE IS WRONG. Use this instead:
$().ready(function () {
var url = 'http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&minx=-30&miny=0&maxx=0&maxy=150&callback=?';
$.get(url, function (data) {
// can use 'data' in here...
});
});
For the record, as far as I can tell, you had two problems:
You weren't passing a "jsonp" type specifier to your $.get, so it was using an ordinary XMLHttpRequest. However, your browser supported CORS (Cross-Origin Resource Sharing) to allow cross-domain XMLHttpRequest if the server OKed it. That's where the Access-Control-Allow-Origin header came in.
I believe you mentioned you were running it from a file:// URL. There are two ways for CORS headers to signal that a cross-domain XHR is OK. One is to send Access-Control-Allow-Origin: * (which, if you were reaching Flickr via $.get, they must have been doing) while the other was to echo back the contents of the Origin header. However, file:// URLs produce a null Origin which can't be authorized via echo-back.
The first was solved in a roundabout way by Darin's suggestion to use $.getJSON. It does a little magic to change the request type from its default of "json" to "jsonp" if it sees the substring callback=? in the URL.
That solved the second by no longer trying to perform a CORS request from a file:// URL.
To clarify for other people, here are the simple troubleshooting instructions:
If you're trying to use JSONP, make sure one of the following is the case:
You're using $.get and set dataType to jsonp.
You're using $.getJSON and included callback=? in the URL.
If you're trying to do a cross-domain XMLHttpRequest via CORS...
Make sure you're testing via http://. Scripts running via file:// have limited support for CORS.
Make sure the browser actually supports CORS. (Opera and Internet Explorer are late to the party)
You need to maybe add a HEADER in your called script, here is what I had to do in PHP:
header('Access-Control-Allow-Origin: *');
More details in Cross domain AJAX ou services WEB (in French).
For a simple HTML project:
Python 2
cd project
python -m SimpleHTTPServer 8000
Python 3
cd project
python -m http.server 8000
Then browse your file.
Works for me on Google Chrome v5.0.375.127 (I get the alert):
$.get('http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=?&minx=-30&miny=0&maxx=0&maxy=150',
function(json) {
alert(json.photos[1].photoUrl);
});
Also I would recommend you using the $.getJSON() method instead as the previous doesn't work on IE8 (at least on my machine):
$.getJSON('http://www.panoramio.com/wapi/data/get_photos?v=1&key=dummykey&tag=test&offset=0&length=20&callback=?&minx=-30&miny=0&maxx=0&maxy=150',
function(json) {
alert(json.photos[1].photoUrl);
});
You may try it online from here.
UPDATE:
Now that you have shown your code I can see the problem with it. You are having both an anonymous function and inline function but both will be called processImages. That's how jQuery's JSONP support works. Notice how I am defining the callback=? so that you can use an anonymous function. You may read more about it in the documentation.
Another remark is that you shouldn't call eval. The parameter passed to your anonymous function will already be parsed into JSON by jQuery.
As long as the requested server supports the JSON data format, use the JSONP (JSON Padding) interface. It allows you to make external domain requests without proxy servers or fancy header stuff.
If you are doing local testing or calling the file from something like file:// then you need to disable browser security.
On MAC:
open -a Google\ Chrome --args --disable-web-security
It's the same origin policy, you have to use a JSON-P interface or a proxy running on the same host.
We managed it via the http.conf file (edited and then restarted the HTTP service):
<Directory "/home/the directory_where_your_serverside_pages_is">
Header set Access-Control-Allow-Origin "*"
AllowOverride all
Order allow,deny
Allow from all
</Directory>
In the Header set Access-Control-Allow-Origin "*", you can put a precise URL.
In my case, same code worked fine on Firefox, but not on Google Chrome. Google Chrome's JavaScript console said:
XMLHttpRequest cannot load http://www.xyz.com/getZipInfo.php?zip=11234.
Origin http://xyz.com is not allowed by Access-Control-Allow-Origin.
Refused to get unsafe header "X-JSON"
I had to drop the www part of the Ajax URL for it to match correctly with the origin URL and it worked fine then.
As final note the Mozilla documentation explicitly says that
The above example would fail if the header was wildcarded as:
Access-Control-Allow-Origin: *. Since the Access-Control-Allow-Origin explicitly mentions http://foo.example,
the credential-cognizant content is returned to the invoking web
content.
As consequence is a not simply a bad practice to use '*'. Simply does not work :)
Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp:
function AjaxFeed(){
return $.ajax({
url: 'http://somesite.com/somejsonfile.php',
data: {something: true},
dataType: 'jsonp',
/* Very important */
contentType: 'application/json',
});
}
function GetData() {
AjaxFeed()
/* Everything worked okay. Hooray */
.done(function(data){
return data;
})
/* Okay jQuery is stupid manually fix things */
.fail(function(jqXHR) {
/* Build HTML and update */
var data = jQuery.parseJSON(jqXHR.responseText);
return data;
});
}
I use Apache server, so I've used mod_proxy module. Enable modules:
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
Then add:
ProxyPass /your-proxy-url/ http://service-url:serviceport/
Finally, pass proxy-url to your script.
For PHP - this Work for me on Chrome, safari and firefox
https://w3c.github.io/webappsec-cors-for-developers/#avoid-returning-access-control-allow-origin-null
header('Access-Control-Allow-Origin: null');
using axios call php live services with file://
I also got the same error in Chrome (I didn't test other browers). It was due to the fact that I was navigating on domain.com instead of www.domain.com. A bit strange, but I could solve the problem by adding the following lines to .htaccess. It redirects domain.com to www.domain.com and the problem was solved. I am a lazy web visitor so I almost never type the www but apparently in some cases it is required.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]
Make sure you are using the latest version of JQuery. We were facing this error for JQuery 1.10.2 and the error got resolved after using JQuery 1.11.1
Folks,
I ran into a similar issue. But using Fiddler, I was able to get at the issue. The problem is that the client URL that is configured in the CORS implementation on the Web API side must not have a trailing forward-slash. After submitting your request via Google Chrome and inspect the TextView tab of the Headers section of Fiddler, the error message states something like this:
*"The specified policy origin your_client_url:/' is invalid. It cannot end with a forward slash."
This is real quirky because it worked without any issues on Internet Explorer, but gave me a headache when testing using Google Chrome.
I removed the forward-slash in the CORS code and recompiled the Web API, and now the API is accessible via Chrome and Internet Explorer without any issues. Please give this a shot.
Thanks,
Andy
There is a small problem in the solution posted by CodeGroover above , where if you change a file, you'll have to restart the server to actually use the updated file (at least, in my case).
So searching a bit, I found this one To use:
sudo npm -g install simple-http-server # to install
nserver # to use
And then it will serve at http://localhost:8000.

access to restricted uri denied on jquery includes - works fine with www subdomain

For some reason the jquery includes on this page throws a 1012 error but only if I view this page from the domain without the www
http://marchofdimes.com/ovulation_calendar.html
The error doesn't show up from the www subdomain.
http://www.marchofdimes.com/ovulation_calendar.html
I could change the script src to include a full path name, I suppose that might solve the problem but wanted to ask why it's happening in the first place. And the recommended fix.
Thanks
The problem is the ajax call you make with this line
$("#result_message").load('http://www.marchofdimes.com/hs.xsl/oc_Form.xml',..
change it to
$("#result_message").load('/hs.xsl/oc_Form.xml',...
The issue is that an ajax call from the non-www to the www violates the same origin policy
more info at
http://en.wikipedia.org/wiki/Same_origin_policy
https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript
You have:
$("#result_message").load('http://www.marchofdimes.com/hs.xsl/oc_Form.xml', { //ajax call to dynament
www.marchofdimes.com is a different hostname to marchofdimes.com, so you hit the same origin policy.
Use a relative URI (i.e. one that starts with a /hs.xsl and not http://.
Alternatively, pick one hostname to be canonical and redirect (with a 301 status) all requests from the other to it.

"Access is denied" error on accessing iframe document object

For posting AJAX forms in a form with many parameters, I am using a solution of creating an iframe, posting the form to it by POST, and then accessing the iframe's content.
specifically, I am accessing the content like this:
$("some_iframe_id").get(0).contentWindow.document
I tested it and it worked.
On some of the pages, I started getting an "Access is denied" error. As far as I know, this shouldn't happen if the iframe is served from the same domain.
I'm pretty sure it was working before. Anybody have a clue?
If I'm not being clear enough: I'm posting to the same domain. So this is not a cross-domain request. I am testing on IE only.
P.S. I can't use simple ajax POST queries (don't ask...)
Solved it by myself!
The problem was, that even though the correct response was being sent (verified with Fiddler), it was being sent with an HTTP 500 error code (instead of 200).
So it turns out, that if a response is sent with an error code, IE replaces the content of the iframe with an error message loaded from the disk (res://ieframe.dll/http_500.htm), and that causes the cross-domain access denied error.
Beware of security limitations associated to iFrames, like Cross domain restriction (aka CORS). Below are 3 common errors related to CORS :
Load an iFrame with a different domain. (Ex: opening "www.foo.com" while top frame is "www.ooof.com")
Load an iFrame with a different port: iFrame's URL port differs from the one of the top frame.
Different protocols : loading iFrame resource via HTTPS while parent Frame uses HTTP.
My issue was the X-Frame-Options HTTP header. My Apache configuration has it set to:
Header always append X-Frame-Options DENY
Removing it allowed it to work. Specifically in my case I was using iframe transport for jQuery with the jQuery file upload plugin to upload files in IE 9 and IE 10.
I know this question is super-old, but I wanted to mention that the above answer worked for me: setting the document.domain to be the same on each of the pages-- the parent page and the iframe page. However in my search, I did find this interesting article:
http://softwareas.com/cross-domain-communication-with-iframes
Note if you have a iframe with src='javascript:void(0)' then javascript like frame.document.location =... will fail with Access Denied error in IE. Was using a javascript library that interacts with a target frame. Even though the location it was trying to change the frame to was on the same domain as parent, the iframe was initially set to javascript:void which triggered the cross domain access denied error.
To solve this I created a blank.html page in my site and if I need to declare an iframe in advance that will initially be blank until changed via javascript, then I point it to the blank page so that src='/content/blank.html' is in the same domain.
Alternatively you could create the iframe completely through javascript so that you can set the src when it is created, but in my case I was using a library which reqired an iframe already be declared on the page.
Basically, this error occurs when the document in frame and outside of ii have different domains. So to prevent cross-side scripting browsers disable such execution.
if it is a domain issue (or subdomain) such as www.foo.com sending a request to www.api.foo.com
on each page you can set the
document.domain = www.foo.com
to allow for "cross-domain" permissions

Categories

Resources