Chrome-Fetch API无法加载文件.解决方法 [英] Chrome - Fetch API cannot load file. How to workaround?

查看:2007
本文介绍了Chrome-Fetch API无法加载文件.解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个文件:

index.html

<html>
<head>
<meta charset="utf-8" />
<title>Web Page</title>
<style type="text/css">
.text {
    display: inline-block;
    font-family: tahoma;
    font-size: 14px;
    max-width: 400px;
    background-color: #ddedff;
    padding: 10px;
    text-align: justify;
}
</style>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    get_data('info.txt');
});
function get_data(file) {
    var request = new Request(file);
    fetch(request).then(function(response) {
        return response.text().then(function(text) {
            $('.text').html(text);
        });
    });
}
</script>
</head>
<body>
    <div class="text"></div>
</body>
<html>

info.txt

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

当我在Mozilla Firefox上打开文件时:通过本地URIREADME.html:

When I open on Mozilla Firefox the file: README.html through this local URI:

file:///C:/testing/README.html

它能按预期工作,我的意思是文件info.txt上的文本正确显示.

it works as expected, I mean, the text on file: info.txt is displayed properly.

但是当我在Google Chrome上打开相同的URI时,出现黑屏,并且在控制台上出现以下错误:

But when I open the same URI on Google Chrome I get a blank screen and the following error on the console:

README.html:26 Fetch API cannot load file:///C:/testing/README.md. URL scheme must be "http" or "https" for CORS request.
get_data @ README.html:26
README.html:26 Uncaught (in promise) TypeError: Failed to fetch
    at get_data (README.html:26)
    at HTMLDocument.<anonymous> (README.html:21)
    at l (jquery.min.js:2)
    at c (jquery.min.js:2)

您有什么办法可以像在Mozilla Firefox上那样在Google Chrome上打开本地文件?

Do you have what can I do so I can open local files on Google Chrome as I can do on Mozilla Firefox?

如果我需要做一些调整:

If I have to do some tweak on:

chrome://flags/

对我来说可以接受.

编辑

我尝试从命令行启动带有标志--allow-file-access-from-filesGoogle Chrome,这是推荐的此处,但现在出现以下错误:

I tried launching Google Chrome from the command line with the flag: --allow-file-access-from-files as recommended here but now I get the following error:

README.html:26 Fetch API cannot load file:///C:/testing/README.md. URL scheme "file" is not supported.
get_data @ README.html:26
README.html:26 Uncaught (in promise) TypeError: Failed to fetch
    at get_data (README.html:26)
    at HTMLDocument.<anonymous> (README.html:21)
    at l (jquery.min.js:2)
    at c (jquery.min.js:2)

谢谢!

推荐答案

对于Chrome,您仍然需要--allow-file-access-from-files(我建议安装

For chrome you still need --allow-file-access-from-files (and I recommend installing a separate chrome and using it solely for these projects to stay secure), but just shim fetch() for XMLHttpRequest for file:// requests:

if (/^file:\/\/\//.test(location.href)) {
    let path = './';
    let orig = fetch;
    window.fetch = (resource) => ((/^[^/:]*:/.test(resource)) ?
        orig(resource) :
        new Promise(function(resolve, reject) {
            let request = new XMLHttpRequest();

            let fail = (error) => {reject(error)};
            ['error', 'abort'].forEach((event) => { request.addEventListener(event, fail); });

            let pull = (expected) => (new Promise((resolve, reject) => {
                if (
                    request.responseType == expected ||
                    (expected == 'text' && !request.responseType)
                )
                    resolve(request.response);
                else
                    reject(request.responseType);
            }));

            request.addEventListener('load', () => (resolve({
                arrayBuffer : () => (pull('arraybuffer')),
                blob        : () => (pull('blob')),
                text        : () => (pull('text')),
                json        : () => (pull('json'))
            })));
            request.open('GET', resource.replace(/^\//, path));
            request.send();
        })
    );
}

此垫片将;

  • 仅激活本地打开的html文件(外部if语句),
  • 对于未指定协议的任何网址(因此非file://请求)调用普通的fetch(),并且
  • 将相对于当前路径的绝对路径(/root/bob.html)替换为绝对路径(因为危险地评估为C:\或等效路径)
  • only activate for html files opened locally (outer if statement),
  • call the normal fetch() for any url that doesn't specify protocol (and thus non-file:// requests), and
  • will replace absolute paths (/root/bob.html) with ones relative to the current path (since that would dangerously evaluate to C:\ or equivalent)

如果您的index.html实际上不在项目的根目录,请将path设置为其他内容.
如果您需要对
init 的支持,或者text()以外的任何内容,都需要添加.
明确的file://请求将不会得到满足,这是有目的的,但是如果您真的确实知道自己在做什么,那么您将知道如何为您完成这项工作,如果您不这样做,你不应该.

Set path to something else if your index.html isn't actually at the root for the project.
If you need support for init, or anything other than text(), you'll need to add it.
Explicit file:// requests wont be fulfilled, that's on purpose, but if you really do know what you're doing, you'll know how to make this work for you, and if you don't you shouldn't.

如果要对多个文件执行以下操作,则以下内容很有用.将'./'换为document.currentScript.getAttribute('data-root').现在,您可以将该代码段放入其自己的文件中,例如filesystemHelper.js,然后在各个文件中这样调用:

The following is useful if you're going to be doing this for multiple files. Swap out './' for document.currentScript.getAttribute('data-root'). Now you can put that snippet into its own file, say filesystemHelper.js, and call like so in the various files:

<script src="../filesystemHelper.js" data-root="../"></script>

漂亮时髦.

这篇关于Chrome-Fetch API无法加载文件.解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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