pass input file to background script

☆樱花仙子☆ 提交于 2020-01-01 15:04:23

问题


I want to pass the input file from content page to extension background script, and then load it with FileReader() in the extension background script.

So in the web page I have a <input type="file"> and from onchange event I pass the file from content script to background page like this:

 var myfile = document.getElementById('fileid').files[0];
 chrome.runtime.sendMessage({myevent: "start", inputfile: myfile}, function(response) {});

in the background script I have this:

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){

   if(message.myevent==="start")
   {
      var reader = new FileReader();

         reader.onload = function(e) {
              // file is loaded 
         }  


       reader.readAsArrayBuffer(message.inputfile);
   }
});

but FileReader not load it, I'm not sure if this is correct way , but all i need is to pass the input file element to background script and load it with FileReader to send it with HTTP POST from background script. Please tell me what is wrong or how to do it correctly. It will help a lot if I see a sample code, because I'm new to chrome extension development, and not so experienced.


回答1:


All messages send through the Chrome extension messaging API MUST be JSON-serializable. If you want to get the contents of a file at the background page, you'd better create a (temporary) URL for the File object, pass this URL to the background page and use XMLHttpRequest to grab its contents:

// Create URL
var url = URL.createObjectURL(myfile);
// Pass URL to background page (ommited for brevity) and load it..
var x = new XMLHttpRequest();
x.onload = function() {
     var result = x.response;
     // TODO: Use [object ArrayBuffer]
};
x.open('GET', url); // <-- blob:-url created in content script
x.responseType = 'arraybuffer';
x.send();

Though why do you want to send the file to the background page? Content scripts can also send cross-origin requests.



来源:https://stackoverflow.com/questions/24193578/pass-input-file-to-background-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!