I have the following use case:
In a chrome extension page (that is, window.html) I need to show a link/button that will allow a user to select one or more files from the local system. These files will then loaded and processed by the plugin.
Approach: Use an input type=file
to spawn the file open dialog and then handle change
event of that input.
My problem: When I click the button in the popup window, the Open files dialog appears BUT the popup hides away and the javascript code dies. As a workaround, if I right click on the plugin, select "Inspect popup", the popup window no longer closes and the script behind the button runs.
How can I make my javascript run after the user selected the files? (or prevent the popup window closing?)
Code snippets (only relevant lines)
window.html
<input id="csv_multiple_load_win" type=file name=files[] multiple />
(the <input>
tag is not included in form
tag)
window.js
$( document ).ready(function() {
....
$('#csv_multiple_load_win').bind('change', function(event){
alert("Happy to process the "+event.target.files.length+" files!");
});
....
}
What I tried:
*returning false from the event handler
*include the input
in a form
*putting the loading script in background.js like in Upload File as a Form Data through chrome extension question. I tried both approaches. The one in the question and the one in the answer.
*I tried to manually spawn some sort of file dialog (like you would do in a regular code) but I gave up early when I read about some security policies that restricts access to the user file system.
Please help!
EDIT: The solution
As @Xan commented, there is no way to prevent the lost focus. When the focus is lost, the window closes and the javascript is killed.
My workaround was to place the code in another pair of html/js files, namely new_popup.html/js
. The 'new_popup.html' will contain the <input ...
tag and the 'new_popup.js' the event handling as in previous snippets.
The trick is to spawn a new window that will have this 'new_popup.html' as content. To do this in chrome you have two choices: As a new tab and as a standalone window.
First, you have to create an url to your 'new_popup.html' file which is placed inside the extension:
var popup_url = chrome.extension.getURL("new_popup.html");
Then, create a new tab in the active window (esp if you want to show more information that maybe will be refreshed):
chrome.tabs.create({"url":popup_url}, function(tab){
alert("Tab with id: "+tab.id+" created!");
});
or open a new window (I tried to change the style but they all look the same to me)
chrome.windows.create({"url":popup_url, focused:true,type:'panel',
width:600, height:250},function(win){
alert("Popup win created!");
});
Good luck!