本地javascript无法打开本地文件 [英] Local javascript cannot open local file

查看:84
本文介绍了本地javascript无法打开本地文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我,为什么本地javascript无法打开本地文件?我正在尝试创建一个将在本地文件系统上的本地计算机上运行的简单javascript/html应用程序.该应用正在尝试使用其他方法读取配置文件(json),但出现以下错误(Chrome):

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. 对于XMLHttpRequest,方法 open("GET",filename,true)引发异常:

XMLHttpRequest无法加载file:///bla-bla-bla.跨源请求仅支持以下协议方案:http,数据,chrome,chrome扩展名,https,chrome-extension-resource.

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.

  • 对于 document.createElement("iframe").src =文件名,我还有另一个例外:

  • In case of document.createElement("iframe").src=filename I have another exception:

    VM596:1未捕获的DOMException:无法从"HTMLIFrameElement"读取"contentDocument"属性:阻止了具有空"原点的框架访问跨域框架."

    VM596:1 Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a cross-origin frame."

  • var f = new File([],filename,{type:"text/plain"}); 的情况下,我得到了File对象,其大小为零,并且完全没有错误.然后,FileReader返回一个空结果.

  • 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 .:是的,我知道-allow-file-access-from-files ,但是我需要由客户来运行.

    P.S.: Yes, I know about --allow-file-access-from-files but I need to run this by customers.

    推荐答案

    要读取.json文件,您可以做的就是将其声明为.js.

    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>
    

    这将打印

    Object {value1: 10, value2: "hello"}
    

    这两个文件都必须位于同一目录中,否则您必须更改data.js的导入.

    Both of them have to be in the same directory, otherwise you've to change the import of data.js.

    这篇关于本地javascript无法打开本地文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆