Chrome - Fetch API 无法加载文件。如何解决?

2024-02-14

我有以下两个文件:

索引.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文件:README.html通过这个本地URI:

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

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

但当我打开同样的URI on Google 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)

你有什么办法我可以打开本地文件吗Google Chrome我能做的Mozilla Firefox?

如果我必须做一些调整:

chrome://flags/

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

EDIT

我尝试启动Google Chrome从带有标志的命令行:--allow-file-access-from-files按照推荐here http://www.chrome-allow-file-access-from-file.com/windows.html但现在我收到以下错误:

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)

Thanks!


对于 chrome 你仍然需要--allow-file-access-from-files(我建议安装一个单独镀铬 https://www.chromium.org/getting-involved/dev-channel并仅将其用于这些项目以保持安全),但只是垫片fetch() for XMLHttpRequest for file://要求:

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陈述),
  • 调用正常的fetch()对于任何未指定协议的 url(因此非file://请求),以及
  • 将替换绝对路径(/root/bob.html)与相对于当前路径的(因为这会危险地评估为C:\或同等学历)

Set path如果你的index.html实际上并不是该项目的根源。
如果您需要支持init https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters,或除text(),您需要添加它。
显式的file://请求不会得到满足,这是故意的,但如果你really知道你在做什么,你就会知道如何让这件事为你工作,如果你不知道,你就不应该这样做。


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

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

相当时髦。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Chrome - Fetch API 无法加载文件。如何解决? 的相关文章

随机推荐