4

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();
  }
});
Community
  • 1
  • 1
briank
  • 61
  • 4

1 Answers1

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;
    }
})
MALIK KHAN
  • 41
  • 1