ajax - Local javascript cannot open local file - Stack Overflow

Please tell me, why local javascript cannot open a local file?I'm trying to create a simple javas

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):

  1. 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.

  2. 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."

  3. 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):

  1. 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.

  2. 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."

  3. 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.

Share Improve this question edited Jan 20, 2017 at 14:08 John Bupit 10.6k9 gold badges44 silver badges79 bronze badges asked Jan 20, 2017 at 14:01 BUKTOPBUKTOP 98011 silver badges28 bronze badges 8
  • 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 to localhost/index.html or localhost/bla-bla-bla.js. Python, for instance, lets you set one up in the current folder via mand line with python -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 in myVariable (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
 |  Show 3 more ments

3 Answers 3

Reset to default 5

Why 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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745215513a4616995.html

相关推荐

  • ajax - Local javascript cannot open local file - Stack Overflow

    Please tell me, why local javascript cannot open a local file?I'm trying to create a simple javas

    3小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信