Поведение FileReader в Javascript (Chrome против Firefox) - PullRequest
0 голосов
/ 01 февраля 2019

JS FileReader API работает в Firefox иначе, чем в Chrome.Когда файл, использующий FileReader, помещается в интервал (в Firefox), он не читает этот файл после обновления.Это происходит из-за того, что Firefox кэширует загруженный файл и, следовательно, не перечитывает файл с интервалом?Эта проблема не возникает в Chrome.

Я создаю утилиту, которая загружает пользовательский CSS в тег стиля в HTML.Я пытался поместить экземпляр FileReader и функцию onload внутри интервала, чтобы каждый раз создавать новый экземпляр - похоже, не работает.

HTML

<p>Hello</p>
<input id="files" type="file">
<div>
    <code class="output"></code>
</div>

JavaScript

const fileReader = new FileReader(); // FileReader instance
fileReader.onload = function () {
    // once the result is resolved, run the output function
    if (fileReader.result) outputToUI(fileReader.result);
};
const textOutput = document.querySelector('.output'); // where the file contents go

setInterval(() => {
    let files = [];
    if (document.querySelector('#files')) {
        files = document.querySelector('#files').files; // grab the FileList => [Array]
        files.length !== 0 ? readText(files) : null; // if there's at least one file, read the text
    }
}, 1000);

function outputToUI(text) {
    textOutput.innerText = ''; // empty out text
    textOutput.innerText = text; // replace with new text
}

function readText(fileList) {
    if (fileList && fileList[0]) {
        fileReader.readAsText(fileList[0]); // read the file as text => FileReader.result
    }
}

Пример ожидаемого поведения будет выглядеть так:

|> interval is made and starts looking for files
=> null

|> user uploads a file (styles.css)
=> body { box-sizing: border-box; }

|> user updates a property and saves the same file (styles.css)
=> body { box-sizing: border-box; margin: 0; }
// still returns "body { box-sizing: border-box; }" in Firefox
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...