I'm building a local html file to show dynamically some data from an XML file and by using Chrome's Inspector I figured my XML file is not being parsed because it is "not hosted on a webserver"
XMLHttpRequest cannot load data.xml. Cross origin requests are only supported for HTTP.
I know that there are a few flags I could pass to Chrome/web browser to workaround this limitation but I'm looking into some alternative method. I will probably have to distribute this files to a few people and teaching them how to pass flags to the browser is not an option for me. Hosting them on a web server is not an option either.
Thanks a lot in advance.
No ghost unless you set up a local server or host the XML file locally. Ajax has to follow the same origin policy.
If you're willing to use a library you can use jQuery's AJAX method to perform a cross-domain request (i'm not entirely certain that jQuery will support what you're trying to do). JSONP works, but you have XML data...
You could try loading it in a script tag anyway and see if you can get the innerHTML value without breaking the script; once you're done getting the text from it, remove the script from the page. You may be able to get at the data before the browser tries to parse the script by attaching onload and onreadystatechange events to the script element.
var s = document.createElement('script');
s.src = '/path/to/file.xml';
s.onload = s.onreadystatechange = getData;
function getData(e)
{
//get the text out of the script element
//remove the event handler from the script element
//remove the script from the page
}
document.getElementsByTagName('body')[0].appendChild(s);
I didn't test it, but it might work.
How about setting up a local webserver? XAMPP should be easy to install even for novice. Just tell them to put your files in the htdocs folder, run xampp and start the apache server.
Unless there's a compelling reason to have a separate html and xml file, you could just put the data directly in the html file.
I'm afraid if chrome only provides options that you don't like to apply, your application and chrome will not come together. Access via iframe & object does'nt work too, load()-method of createDocument is not supported by chrome(if it does I guess you got the same error).
Whatever you try will be a sideway to pass chrome's restrictions, what cannot be good, because I think they have good reasons to setup these restrictions.
Related
I've built a simple html page with javascript in a separate file, called on a button press.
I've opened the html file in chrome, and the path resembles: file:///home/tom/projects/index.html
The javascript needs to read a JSON file (file:///home/tom/projects/mydata.json) which is in the same directory, using a hardcoded path.
I'm really struggling to do this. As I understand, this is because I'm using client side js (meaning I can't use the fs library for example), which is limiting my options.
According to the question here, I can't load the file if I use the URL in the format: file:///home/to.... as it gives me the error:
Cross origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, https.
If I start an HTTP-server, as the answer suggests, I can use server-side modules, but if possible I would like to avoid this.
I've noticed many answers that suggest using a dialog box like this:
var selectedFile = document.getElementById('input').files[0];
function readFile (file_path) {
var reader = new FileReader();
reader.readAsText(file_path);
console.log(reader.substring(0, 100));
};
but I can't make this work with a path in the form: file:///home/tom/projects/mydata.json
Is there a way to load a .json file from a file:///home/to.... format URL using client-side javascript, with a hardcoded path (ie not asking the user to select the file from a selection box)?
This is a deliberate security restriction, to stop a user from being given, and then opening, a HTML page which then tries to read their disk.
Run your page in a webserver (as that question suggested) then you can either load the JSON from a URL (e.g. something like http://localhost/projects/mydata.json) using JavaScript, or use a server-side language to fetch it and display it inside the rendered HTML. Either way will work, the first way is probably simpler and closest to what you've got now.
It's always far better to serve HTML pages from a HTTP server, the way it's intended to be.
There is javascript on my webpage, but I need to hide it from my users (I don't want them to be able to see it because it contains some answers to the game.)
So I tried using Jquery .load in order to hide the content (I load the content from an external js file with that call). But it failed to load. So I tried ajax and it failed too.
Maybe the problem comes from the fact that I'm trying to load a file located in my root directory, while the original page is located in "root/public_html/main/pages":
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url : "../../../secret_code.js",
dataType: "text",
success : function (data) {
$("#ajaxcontent").html(data);
}
});
});
</script>
1) Why can't I load a file from the root directory with ajax or load method?
2) Is there another way around?
PS: I'm putting the file in the root directory so people can't access it directly from their browsers...
1) if the file isn't accessible via web browsers, than it's not accessible via ajax (ajax is part of the web browsers
2) try /secret_code instead of ../../../secret_code.js
What is your system setup? Are you using a CMS?
Even if you add the javascript to the page after page load a user with a tool like firebug can go and view it. I don't think what you are doing is really going to secure it. An alternate solution is that you could minify and obfuscate the javascript that you use in your production environment. This will produce near unreadable but functioning javascript code. There are a number of tools that you can run your code through to minify and obfuscate it. Here is one tool you could use: http://www.refresh-sf.com/yui/
If that isn't enough then maybe you could put the answers to the game on your serverside and pull them via ajax. I don't know your setup so I don't know if that is viable for you.
Navigate to the URL, not the directory. Like
$.ajax({
url : "http://domain.com/js/secret_code.js",
..
Even if you load your content dynamicly, it's quite easy to see content of the file using firebug, fiddler or any kind of proxy. I suggest you to use obfuscator. It will be harder for user to find answer
Take a look at the jQuery.getScript() function, it's designed for loading Javascript files over AJAX and should do what you need.
Try jQuery's $.getScript() method for loading external
Script files, however, you can easily see the contents of the script file using Firebug or the developer toolbar!
Security first
You can't access your root directory with JavaScript because people would read out your database passwords, ftp password aso. if that would be possible.
You can only load files that are accessible directly from browsers, for example, http://www.mydomain.com/secret_code.js
If it can't be accessed directly by the browser, it can't be accessed by the browser via ajax. You can however use .htaccess to prevent users from opening up a js file directly, though that doesn't keep them from looking at it in the google chrome or firebug consoles.
If you want to keep it secret, don't let it get to the browser.
I need to access XML files with JQuery. I tried these two ways but I can't seem to contain them on one browser.
Here:
In Chrome, this works:
var xml = "<music><album>Beethoven</album></music>";
var result = $(xml).find("album").text();
alert(result);
Now I try to use it in conjunction with this code snippet, which works fine in IE:
jQuery.get('fruits.xml', function(data) {
alert(data);
});
The problem is, if I put both these codes together, one of them don't work on the other. So in Chrome I'd be able to access "Beethoven" while not being able to access "fruits.xml" but gives me this error:
XMLHttpRequest cannot load file:///C:/Python32/fruits.xml. Origin null is not allowed by Access-Control-Allow-Origin.
In IE on the other hand, I could access the whole content of fruits.xml and save it into a variable but the code for which I need to access XML attributes which works in Chrome doesn't work in IE.
As you can see, I want to get the contents of the xml using the 2nd snippet of code, while I will access the contents of the xml using the 1st snippet of code. Is there another way to access XML with Javascript? Can you help me with what's wrong with my codes?
Help?
The problem causing the error message is that you're sending an XHRRequest (The A in *A*JAX) to a file:// URL. For security reasons, this is being disabled by modern browsers. Instead, set up a webserver und it to access your page, via http://localhost/.. instead of file://C:/....
For the second part, make sure that you test loading fruits.xml first. Chances are there is an error in the XML stored in this file, or its structure is not what you expect. You can debug JavaScript in IE by pressing F12, going to the Scripting tab, and clicking Start Debugger. That way, you'll get a better error description than "doesn't work".
this may be a bug associated with chrome
loading local files in chrome bug/security feature
Problems with jQuery getJSON using local files in Chrome
Accessing relative URL's via "ajax" from "file://" content
as an advice dont wrap your xml in jquery and parse this way it may vary from browser to browser use instead .parseXML
Say my html file is from http://foo.com/index.html, in it, there's a <script> tag to http://bar.com/bar.js. In bar.js, I want to start a SharedWorker where the url is http://bar.com/worker.js. Is there a way to achieve this (maybe something like jsonp)?
The preferred way to do this sort of cross-domain access these days is using the W3 CORS specification.
Cross-Origin Resource Sharing
However, this might not be suitable for you if you do not control the the site at bar.com. If you do, then CORS is definitely a good option, but you may need to resort to JSONP if bar.com is run by another party, since CORS depends on the site sending back specific headers authorizing your browser to download the resource you requested.
This is a solution I found:
Write the script inside a function (can be an inner function)
get the text using function.toString() (removing the function declaration and closing brace)
append the text to a BlobBuilder and get the blob
Use window.URL.createObjectURL to convert the blob to a url
use that url for the worker
is this possible?
<html>
<script src="local.js>
<script>
// get contents of local.js file here without doing an ajax call?
</script>
</html>
local.js resides on the same server, and I know that by doing an xhr call I can get its contents (if not on file://).
But, as it is already requested synchronously by the browser, its contents is known to the document so I hope there is a way to access it? The document.scripts collection was no help to me.
Somewhat like getting innerHTML (which works for scripts defined in-page)?
I'm not sure on how to get the included javascript code, nor why you would need this, but how about going the other direction?
Instead of having a script tag, make a XHR call to the file and eval its contents + keep its contents as a variable also.
**Disclaimer: I cannot see why you would need this, nor would I actually suggest you use this method, but it's a work-around.
Are you assuming XHR will not use the cached version? It will, there may be a request, but it should be fast (reuse the same HTTP connection) and return 304 (not modified). So the cached version will be used unless your JavaScript file's HTTP response headers prohibit or do not specify caching directives (but usually they should).
I suspect that while the contents of the script are known to the browser, they're not known to the document, and are therefore not accessible via the DOM API. So you will have to use the XHR approach. With a bit of luck, if you ensure the script is properly cached, the XHR request will pull the script contents from the local cache anyway.