简体   繁体   English

在 iPhone 上的新 window 和 iPad Z50DE9BC68C93DC32D8C7C90509 浏览器上打开 Blob URL

[英]Open Blob URL in new window on iPhone and iPad Safari Browsers

I am trying to generate a PDF file based on the response returned from the server and open the file in new tab.我正在尝试根据从服务器返回的响应生成 PDF 文件并在新选项卡中打开该文件。 It works very well in Desktop across all browsers but has problem in apple devices (iphone + ipad) in safari browser.它在所有浏览器的桌面上运行良好,但在 safari 浏览器中的苹果设备(iphone + ipad)中存在问题。

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.我在使用 iOS 14.3 的 iPhone 6s+ 上遇到了同样的问题。 Looks like it's a feature of Safari on iPhone/iPad that blocks popups if the window.open() stays in some various events (for example onload / onloadend event, or setTimeout ).看起来它是 iPhone/iPad 上 Safari 的一个功能,如果window.open()停留在一些不同的事件中(例如onload / onloadend事件或setTimeout ),它会阻止弹出窗口。 You can try moving window.open() into another scope or function to see the results.您可以尝试将window.open()移动到另一个 scope 或 function 以查看结果。

As for my issue, I solve it by creating a hidden anchor tag and then click it:至于我的问题,我通过创建一个隐藏的锚标记然后单击它来解决它:

mySmallDiv.innerHTML = '<a href="+'url'+" target="_blank" id="openPdf">&nbsp;</a>';
document.getElementById("openPdf").click();

But Safari may still blocks it, so please change your code accordingly.但是 Safari 可能仍然会阻止它,所以请相应地更改您的代码。
And, don't forget to call URL.revokeObjectURL(url) after a timeout.而且,不要忘记在超时后调用URL.revokeObjectURL(url)

Besides, I think you need to use FileReader() if the browser is Chrome iOS.此外,如果浏览器是 Chrome iOS,我认为您需要使用FileReader()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM