5

I want to let the user choose and upload a file from the chrome extension popup. But, as soon as the file-chooser dialog opens the popup loses focus and closes immediately. From this answer, the workaround seems to be that I can move the dialog opening logic to the background-page, which is not affected by loss of focus.

I have tried the answer, but the file-chooser does not appear at all. It is weird that fileChooser.click() event does actually occur (I was able to verify it by creating a click listener for fileChooser). Below is a simplified version just to focus on the problem.

popup.html

<button id="uploadCSV">Upload CSV</button> 

popup.js

$('#uploadCSV').click(function() { chrome.extension.sendMessage({ action: 'browseAndUpload' }); }); 

background.js

var fileChooser = document.createElement('input'); fileChooser.type = 'file'; chrome.extension.onMessage.addListener(function (msg) { if (msg.action === 'browseAndUpload') { fileChooser.click(); } }); 
2
  • 1
    Hi, i'm having the same issue, did you manage to find a solution? Commented Jul 3, 2019 at 17:47
  • relevant 8 years old bug still open bugzilla.mozilla.org/show_bug.cgi?id=1292701 (it's Firefox specific but I don't think it matters a lot). Commented Jan 4, 2024 at 16:15

1 Answer 1

0

Popup.js

var file = document.getElementById('#file')[0].files[0]; var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function () { chrome.runtime.sendMessage({ "uploadFile": true, blob: reader.result, file: { name: file.name } }, x => { }) }; reader.onerror = function (error) { console.log('Error: ', error); }; 

Background.js

function dataURLtoFile(dataurl, filename) { var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new File([u8arr], filename, { type: mime }); } function uploadFile(msg) { var file = msg.file; let nfile = dataURLtoFile(msg.blob, file.name) var formData = new FormData(); formData.append('cvFile', nfile); var settings = { "async": true, "crossDomain": true, "url": "endpoint", "method": "POST", "headers": { "accept": "application/json", "cache-control": "no-cache", }, "processData": false, "contentType": false, "mimeType": "multipart/form-data", "data": formData } $.ajax(settings).done(function (response) { console.log(response); }); } chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { switch (!0) { case 'uploadFile' in msg: uploadFile(msg); break; } }) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.