'Open file in browser with FileReader API, triggered by CTRL+O, without user click
I'm doing an app in the browser, and I want to use CTRL+O to open a file and read its content with the FileReader API.
The following code works, but only after a user interaction with mouse:
window.onkeydown = (e) => {
if (e.ctrlKey && event.key === 'o') {
e.preventDefault(); // CTRL + O :
document.getElementById('file-input').click(); // trigger a click on the INVISIBLE file-picker input
return false;
}
}
document.getElementById('file-input').addEventListener('change', (e) => {
var file = e.target.files[0];
if (!file) { return; }
var reader = new FileReader();
reader.onload = function(e) {
console.log(e.target.result);
};
reader.readAsText(file);
}, false);
#file-input { display: none; }
<input type="file" id="file-input" />
However, I'd like to allow the user to do CTRL + O right after the loading of the page, and allow the file to be loaded, even if there is no mouse user interaction.
I get this issue on Firefox:
<input> picker was blocked due to lack of user activation.
On Chrome, it works without problem.
Question: How to allow the user arriving on the webpage to do CTRL + O straightforwardly, without first having to click on buttons to initiate a "user interaction"?
Couldn't a keypress (CTRL+O) be considered as a user interaction?
Note: I'm doing an app for people who mainly use keyboard shortcuts and few mouse clicks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|