In a Chrome Extension with Background and Content scripts when can I call revokeObjectURL?

576 Views Asked by At

I am uploading files from the local file system by using XMLHttpRequest. I am following the suggestion made in this SO question - Pass large blob or file from chrome extension

This is started in the background script with the following code

function uploadLocalFilesAndSend(msg){
var xhr = [], i;
var x = 0;
var filePaths = msg.UploadDocumentFileInfoList;
for (i = 0; i < filePaths.length; i++){
    (function(i){
        xhr[i] = new XMLHttpRequest();
        var url = 'File:///' + filePaths[i].FilePath;
        console.log('uploadLocalFilesAndSend - URL being used: ' + url);
        xhr[i].open('GET', url, true);
        xhr[i].responseType = 'blob';
        xhr[i].onload = function() {
            x += 1;
            var newURL = URL.createObjectURL(xhr[i].response);
                console.log('uploadLocalFilesAndSend - newURL: ' + newURL);
                msg.UploadDocumentFileInfoList[i].PathURL = newURL;
                if (x == filePaths.length) {
                    chrome.tabs.sendMessage(ipasTabID, msg);
                }
        };
        xhr[i].send();
    })(i);
}
}

As each file is uploaded, createObjectURL is used to create a new URL object. These URLS are then passed by message to the Content script. The content script is pretty much identical calling createObjectURL again on the file which produces a new URL. These URLs are then messaged to a webpage where they are then used to get the respective files.

Each time this is done I am effectively creating a set of URL objects in the background script and then a new set in the Content Script.

When should I call revokeObjectURL?

I thought that for the URL objects created in the background script I could call revokeObjectURL only after the content script has retrieved the file and created new URL objects, am I right? Secondly I cannot call revokeObjectURL on the URLs created in the content script until the files are safely uploaded to the webpage.

If I am correct, then can I call revokeObjectURL on the URL that the Background script created in the content script?

0

There are 0 best solutions below