Chrome extension: how to pass ArrayBuffer or Blob from content script to the background without losing its type?

后端 未结 2 747
失恋的感觉
失恋的感觉 2020-12-04 20:14

I have this content script that downloads some binary data using XHR, which is sent later to the background script:

var self = this;
var xhr = new XMLHttpReq         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 20:54

    There is a better way to pass Blob (or ArrayBuffer) between any parts of the same Chrome extension (content scripts, background page and ordinary pages) then creating an ordinary JS Array or a binary string and passing this (sometimes extremely big) chunk of data in a message body! Remember that they are JSONified at the sender's end and then unJSONified at the receiver's end!

    Just create and pass Object URL:

    sendResponse(URL.createObjectURL(blob));
    

    or create Blob first from ArrayBuffer:

    var blob = new Blob([ arrayBuffer ], { type: 'image/jpeg' });
    sendResponse(URL.createObjectURL(blob));
    

    BTW XMLHttpRequest 2 can return both Blob and ArrayBuffer.

    Notes

    • Object URLs can be alive for a qute long time so if you don't need data anymore don't forget to release such URLs calling URL.revokeObjectURL(objectURL)
    • Object URLs as any URL are subject of Cross-Origin restrictions but all parts of your extension are in the same origin of course.
    • BTW: I got a 4x performance boost when start passing such URLs instead of passing data itself in my Chrome extension! (My data were quite big images.)

提交回复
热议问题