0

I am using the message passing API and I'm successfully passing variables between popup and content script, but passing a file isn't working, it returns an empty value to the content script, instead of the file data.

What I already tried is:

Popup:

<input type="file" id="file">
$(document).on('change', '#file', function() {
    var value = this.value;
    var fileName = typeof value == 'string' ? value.match(/[^\/\\]+$/)[0] : value[0];
    var fileData = this.files[0];
    // this prints the file data successfully to console
    console.log(fileData); 
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {action: "sendFile", file: fileData });
    });
});

Content Script:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.hasOwnProperty("action") && request.action == 'sendFile') {
        console.log(file); // <-- empty
    }
});

Is there any limitations in the messages API? or is there something I'm doing wrong?

Thanks.

tinyCoder
  • 350
  • 13
  • 37
  • 1
    Only JSON-compatible data can be transferred like strings, numbers, booleans, and arrays/objects of such types. – wOxxOm Jul 03 '19 at 16:36
  • But the popup console prints json data holding the file information, why not these data being passed to content script as well? – tinyCoder Jul 03 '19 at 16:37
  • In JS the objects may have nonserializable properties (technically the "enumerable" bit is false) that are shown in console for convenience. To view the actual serialization you need to do console.log(JSON.parse(JSON.stringify(yourData))). – wOxxOm Jul 03 '19 at 16:52
  • 1
    See also [Does chrome extension internally use JSON.stiringify to postMessage over to background page?](//stackoverflow.com/a/38263829) – wOxxOm Jul 03 '19 at 17:11
  • Thank you for the great resources, i followed an amazing solution here and that worked: https://stackoverflow.com/questions/21132971/upload-file-as-a-form-data-through-chrome-extension, but it has a problem that the popup closes automatically after the user choose the file, i couldn't prevent that. – tinyCoder Jul 03 '19 at 17:29

1 Answers1

0

As @wOxxOm mentioned in the comments, seems that the data being passed is being stringified, thus, files will not go through.

However, I found a great solution to my question here:

https://stackoverflow.com/a/36930012/2654691

tinyCoder
  • 350
  • 13
  • 37