简体   繁体   中英

virtual <input type=“file”> element - unreliable onchange event - why?

My system is Windows 10, Chrome stable 59. Issue is also observed in mobile Chrome (Android).

I have a project in html/js - https://github.com/f3flight/html-storyboard hosted here - http://us.3ft.ru/draw/

My current problem is that sometimes (and more so on mobile devices - Android phone & tablet) the "LOAD A" and "LOAD" buttons which create input element and then programmatically "click" on it https://github.com/f3flight/html-storyboard/blob/master/js.js#L285 , https://github.com/f3flight/html-storyboard/blob/master/js.js#L346 , sometimes after a file has been selected in browser and selection window/app closes (on Android I test with both "documents" app and "Camera" app), the "onchange" event does not fire. There's a DBG button right now on the page which opens a console at the bottom where the issue can be monitored as a single "load_all" or "load" line with no further debug output (there should be a lot). I feel like the issue happens more on Android then on desktop, but I do see it on desktop too.

Can it be that the virtual "input" element gets garbage collected (I do not add it to DOM since I don't want to manually clean up later) before the file selection has finished? I thought of this as unlikely but I don't know the internals of the browser.

Ok I've figured this one myself. I was right in my assumption - the "input" element was erased from memory before it's onchange event was called - that is if I never stored any reference to it outside of the function where I created it and called onclick.

I fixed this by creating a module-scoped variable: https://github.com/f3flight/html-storyboard/blob/master/board.js#L14 I assign to it when creating input element instead of allocating a new variable. This is enough to fix the issue.

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