I am trying to generate a PDF file based on the response returned from the server and open the file in new tab. It works very well in Desktop across all browsers but has problem in apple devices (iphone + ipad) in safari browser.
Here is the code snippet:
if (responseType = base64 encoded string like JVBERi0xLjUKJeLjz9MKMSAwI....) {
const binaryString = window.atob(fileResponseData);
const bytes = new Uint8Array(binaryString.length);
const binaryToBlob = bytes.map((byte, i) => binaryString.charCodeAt(i));
const blob = new Blob([binaryToBlob], { type: 'application/pdf' });
this.downloadFile(blob, fileName);
} else {
// blob response like %PDF-1.7 %âãÏÓ5 0 obj....
const blob = new Blob([fileResponseData], { type: 'application/pdf' });
this.downloadFile(blob, fileName);
}
This is how I am downloading the file
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
return;
}
const url = (window.URL || window.webkitURL).createObjectURL(blob);
window.open(url, '_blank');
I know there are related articles regarding this topic, but they didn't solved my problem. Infact I came up with above code referring to those articles itself but still I am facing problem in apple devices. As soon as I click button to generate file and display in new tab, nothing happens on apple device, but other devices works just fine.
I have the same problem on my iPhone 6s+ using iOS 14.3. Looks like it's a feature of Safari on iPhone/iPad that blocks popups if the
window.open()stays in some various events (for exampleonload/onloadendevent, orsetTimeout). You can try movingwindow.open()into another scope or function to see the results.As for my issue, I solve it by creating a hidden anchor tag and then click it:
But Safari may still blocks it, so please change your code accordingly.
And, don't forget to call
URL.revokeObjectURL(url)after a timeout.Besides, I think you need to use
FileReader()if the browser is Chrome iOS.