简体   繁体   中英

<input type=“file”> change event firing again when navigating back to the page

I have a very basic file uploader. I upload a file, which triggers the change event (console.log). I navigate to a different page, then press the back button. The change event triggers again (the event is logged again to the console).

I am using Chrome. It doesn't happen with text inputs; only file. Anyone know why?

<input type="file" />

<script>
    const input = document.querySelector("input[type=file]");
    input.addEventListener("change", console.log, { once: true });
</script>

Using Chromium (Brave) the file seems to be cached. So, when you go back, the file is loaded back into the input, triggering the change event.

One workaround would be to set the inputs value to an empty string on page-load:

<input type="file" />

<script>
    const input = document.querySelector('input[type=file]');

    window.addEventListener('load', () => (input.value = ''));
    input.addEventListener('change', console.log);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM