Chrome-Fetch API无法加载文件。解决方法

dav*_*esp 7 javascript firefox google-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>
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

当我打开Mozilla Firefox文件时:README.html通过此本地URI

file:///C:/testing/README.html
Run Code Online (Sandbox Code Playgroud)

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

但是,当我在上面打开它时URIGoogle Chrome出现空白屏幕,并且在控制台上出现以下错误:

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)
Run Code Online (Sandbox Code Playgroud)

你有我能做些什么,所以我可以打开本地文件Google Chrome,我可以做Mozilla Firefox

如果我必须做一些调整:

chrome://flags/
Run Code Online (Sandbox Code Playgroud)

这对我来说是可以接受的。

编辑

我尝试Google Chrome从命令行使用标志启动:--allow-file-access-from-files如此处建议的那样但是现在出现以下错误:

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)
Run Code Online (Sandbox Code Playgroud)

谢谢!

Has*_*own 6

对于铬,你仍然需要--allow-file-access-from-files(我建议安装一个单独的铬和仅使用它的这些项目保持安全性),但只是垫片fetch()用于XMLHttpRequestfile://请求:

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();
        })
    );
}
Run Code Online (Sandbox Code Playgroud)

这个垫片会;

  • 仅对本地打开的 html 文件激活(外部if语句),
  • fetch()为任何未指定协议(因此非file://请求)的url调用法线,以及
  • 将用/root/bob.html相对于当前路径的路径替换绝对路径 ( ) (因为这会危险地评估为C:\或等效)

path如果您index.html实际上不是项目的根,请设置为其他内容。
如果您需要对init或其他任何东西的支持,则text()需要添加它。
明确的file://请求不会被满足,这是故意的,但如果你真的知道你在做什么,你就会知道如何让这对你有用,如果你不知道,你就不应该。


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

<script src="../filesystemHelper.js" data-root="../"></script>
Run Code Online (Sandbox Code Playgroud)

相当时髦。

  • 你如何使用这个代码? (2认同)