I want the user to be able to upload text files as input through the browserAction
popup for my extension, but I've run into a bit of a problem.
I've been using a hidden input
tag, which I trigger with click()
when the user clicks on the file upload button. The file browser dialog opens and all seems to work well, until the popup itself closes. And because of the 'webpage' containing the input
tag closing, the change
event never fires.
Since the extension already has a background script for populating the popup with persistent data, I figured that I could create the input
in the background script and trigger that with .click()
when user clicks on the file upload button in the popup.
But, even though the click event fires for the input
in the background script, the file browser dialog does not open.
I figure that reason for this is that Chrome does not allow the file input to be triggered programatically unless it's through a user action, but I'm not sure. This is how I tried;
popup.js
//Button in popup which should open file broswer dialog
//when clicked
browseBtn.addEventListener('click', function() {
chrome.runtime.sendMessage({msg: 'file_input'});
}
background.js
var fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'text/*';
fileInput.addEventListener('click', function(e) {
console.log('fileInput clicked');
}, false);
fileInput.addEventListener('change', function(e) {
console.log('fileInput changed');
console.log(this.files);
}, false);
chrome.runtime.onMessage.addListener(function(e) {
if(e.msg === 'file_input')
fileInput.click();
});
I know that the click
event is triggered because fileInput clicked
is logged. But, the file browser dialog does not open.
I also tried a variation of this code using chrome.extension.getBackgroundPage()
to directly call fileInput.click()
. Again, click
event was fired but the dialog did not open.
My question is; is there a way to allow the background script to trigger the file input
to open the file browser dialog? That would be the best solution, because it would allow the extension to extract the data from the specified file even if the popup closed somehow.
If not, is there a way to avoid the popup from being closed when the file browser dialog opens? From what I found, using the hidden input
tag was supposed to be a work around, and it does work for some cases, but not for all users.
For example, I was able to upload files without popup being closed on Chrome, Windows 7. But, on Chromium, Ubuntu 14.04, the popup closes the instant the file browser dialog opens.
Any help is appreciated.
It looks like this might have just been fixed, I'm waiting for it to be available as well!