amitdey
amitdey

Reputation: 11

fetch response blob as object HTML element data in edge

In my HTML5+JS Website, I am invoking a webservice by making a HTTP GET call with some header values. This call returns a pdf binary file. My goal is to display the pdf to the user. The following code works well in chrome, but not in edge. In edge, it throws an "Access Denied" error. Is there a work around I can use for edge ?

I cannot set the url directly to data of object, or src of embed tag because the webservice requires specific header values to be present.

fetch(someUrl,{headers:someHeaders})
.then(response=>{return response.blob();})
.then(blob=>{
    pdfObject = document.createElement('object');
    pdfObject.type = 'application/pdf';
    pdfObject.data = URL.createObjectURL(blob);
});

Expected : pdf is displayed Actual : "Access Denied" in developer tools console

Upvotes: 0

Views: 1180

Answers (1)

BlueWater86
BlueWater86

Reputation: 1817

This has been answered a lot of times in the past. Here is a function that handles download of a blob. I use this in several production systems. Browsers unit tested include IE9+, Edge, Chrome, Firefox:

async function showBlobInBrowser(blob, fileName) {
    return new Promise((resolve, reject) => {
        try {
            if (navigator.msSaveOrOpenBlob) {
                navigator.msSaveOrOpenBlob(blob, fileName);
                resolve()
            } else if (window.navigator.msSaveBlob) {
                window.navigator.msSaveBlob(blob, fileName);
                resolve()
            } else {
                const url = (window.URL || window.webkitURL).createObjectURL(blob),
                    a = document.createElement("a")
                a.setAttribute("href", url)
                a.setAttribute("download", fileName)
                a.style.display = "none"
                document.body.appendChild(a)
                a.click()
                setTimeout(function () {
                    a.remove()
                    window.URL.revokeObjectURL(url)
                    resolve()
                }, 0)
            }
        } catch(ex) {
            reject(ex)
        }
    })
}

Upvotes: 1

Related Questions