admin管理员组文章数量:1415664
Please tell me, why local javascript cannot open a local file? I'm trying to create a simple javascript/html app that shall run on the local machine from local filesystem. This app is trying to read the configuration file (json) using different methods, but gets the following errors (Chrome):
In case of XMLHttpRequest, method
open("GET", filename, true)
throws an exception:XMLHttpRequest cannot load file:///bla-bla-bla. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
In case of
document.createElement("iframe").src=filename
I have another exception:VM596:1 Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a cross-origin frame."
In case of
var f=new File([], filename, { type: "text/plain" });
I've got the File object with the zero size and no errors at all. FileReader returns an empty result then.
So, my questions are: Why is it "cross-origin"? These files are stored in the same directory! And how could I open the local file from the same origin/directory I run the script? Please help.
P.S.: Yes, I know about --allow-file-access-from-files
but I need to run this by customers.
Please tell me, why local javascript cannot open a local file? I'm trying to create a simple javascript/html app that shall run on the local machine from local filesystem. This app is trying to read the configuration file (json) using different methods, but gets the following errors (Chrome):
In case of XMLHttpRequest, method
open("GET", filename, true)
throws an exception:XMLHttpRequest cannot load file:///bla-bla-bla. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
In case of
document.createElement("iframe").src=filename
I have another exception:VM596:1 Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a cross-origin frame."
In case of
var f=new File([], filename, { type: "text/plain" });
I've got the File object with the zero size and no errors at all. FileReader returns an empty result then.
So, my questions are: Why is it "cross-origin"? These files are stored in the same directory! And how could I open the local file from the same origin/directory I run the script? Please help.
P.S.: Yes, I know about --allow-file-access-from-files
but I need to run this by customers.
-
2
The
file://
protocol really has a very limited usage oriented for testing or viewing one individual file. For true webapp testing, you'll want to set up a small, basic "web server" program which can take requests tolocalhost/index.html
orlocalhost/bla-bla-bla.js
. Python, for instance, lets you set one up in the current folder via mand line withpython -m SimpleHttpServer 80
– Katana314 Commented Jan 20, 2017 at 14:05 -
@BbIKTOP, tou can transform the JSON file into a javascript file (add
var myVariable =
to the start of the json file) and then include it using<script src='myfile.js'></script>
the data will be inmyVariable
(object). Not the best solution though but works. – ibrahim mahrir Commented Jan 20, 2017 at 14:13 - They have more that 100 pcs without LAN, running very specific software (gym) and this app is intended to show some advert videoclips. Thats why it is not possible to use such an obvious solution with the webserver an that's why I'm asking here about that. Sure, it is possible not to use a json configuration but put the config into the code, maybe in the separate file. It's not interesting and there's no need to ask nor discuss it here. – BUKTOP Commented Jan 20, 2017 at 14:21
- it's how chrome does things, google has declared it so, and therefore there is nothing you can do about it, short of creating a web extension ... Use firefox, or edge, or internet ex... not, don't use that! – Jaromanda X Commented Jan 20, 2017 at 14:21
- There's absolutely no difference as far as deployment, update or runtime functionality between using a script tag vs xhr ... as for the iframe issue, the code you showed would be pointless, as you've created an iframe that you have "lost" access to, so there's no way to add it to the DOM – Jaromanda X Commented Jan 20, 2017 at 14:26
3 Answers
Reset to default 5Why is it "cross-origin"? These files are stored in the same directory!
Because Chrome considers all file://
URLs to be cross-origin to each other.
And how could I open the local file from the same origin/directory I run the script?
From Chrome? You don't. Not unless you disable CORS entirely with a mand-line option (which is a bad idea, as it's trivially easy to forget you've set that mand-line option and go surf the web, leaving yourself wide open to exploits cashing in on the fact you've disabled web security).
Other browsers may treat origin null
differently.
Instead, run a local web server and make the files available via the local web server. Then you can access them because it'll be a same-origin http
URL, not a file
URL. Or use any of the dozen or so frameworks that let you write apps in JavaScript (rather than using the browser). Or a simple NodeJS script serving the files (it's about 10 lines long). Etc.
What you can do to read your .json file, is to declare it a .js.
data.js
var data = `{"value1": 10, "value2": "hello"}`
index.html
<script src="data.js"></script>
<script>
console.log(JSON.parse(data))
</script>
This will print
Object {value1: 10, value2: "hello"}
Both of them have to be in the same directory, otherwise you've to change the import of data.js.
A little late for this party, but I had the same issue and this was how I got around the problem
Create a js template such as this:
template.js
(function(global, factory) {
"use strict";
factory(global);
})(typeof window !== "undefined" ? window : this, function(window) {
"use strict";
var myObjectJson = '<JSONREPLACE>';
var myObject = JSON.parse(myObjectJson);
window.myObject = myObject;
});
Then, have your json replace the tag either by your program that could generate the exported js itself, or create a batch script file that does that for you. I'm using C# so I just build the template directly from there. If the language you're working on is half-decent, you should be able to generate and export your file.
Make sure you use a minified json string.
Then you use your generated file just like you'd use jQuery
<script src="generated.js"></script>
and access your object with
window.myObject;
It's slightly more plicated to set-up, but once you do, you pletely remove the cross-origin issue.
本文标签: ajaxLocal javascript cannot open local fileStack Overflow
版权声明:本文标题:ajax - Local javascript cannot open local file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745215512a2648141.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论