根据 Chrome 版本 >=60 的 PDF 查看功能,通过任何顶层框架导航选项,如
<A HREF=”data:…”>
window.open(“data:…”)
window.location = “data:…”
已被 Google 屏蔽,相关讨论可在 Google Groups 找到.现在的问题是如何在不明确或强制下载 PDF 的情况下在 Web 上显示 PDF。我的旧代码如下所示 window.open
查看PDF数据
dataFactory.getPDFData(id, authToken)
.then(function(res) {
window.open("data:application/pdf," + escape(res.data));
},function(error){
//Some Code
}).finally(function(){
//Some Code
});
在上面我从服务器提取 PDF 数据并显示它。但是因为 window.open
被 Chrome 阻止,正如一位专家在 here 上所建议的那样使用 <iframe>
打开 PDF 数据,我试过了,但没有用。总是提示加载PDF数据失败,如下所示
<iframe>
的更新 JS 代码看起来如下:
dataFactory.getPDFData(id, authToken)
.then(function(res) {
$scope.pdfData = res.data;
},function(error){
//Some Code
}).finally(function(){
//Some Code
});
HTML 如下所示:
<iframe src="data:application/pdf;base64,pdfData" height="100%" width="100%"></iframe>
如何继续并恢复原始 PDF 查看功能?我搜索了其他堆栈问题,但运气不好如何解决这个问题。可能是我在 iframe 代码中做错了什么或遗漏了什么,但没有成功。
最佳答案
在找不到想要的结果后,我想出了以下方法来解决问题。 我没有在新页面上打开 PDF,而是在用户单击“打印”按钮后立即自动下载 PDF 文件。以下是相同的来源。
//File Name
var fileName = "Some File Name Here";
var binaryData = [];
binaryData.push(serverResponse.data); //Normal pdf binary data won't work so needs to push under an array
//To convert the PDF binary data to file so that it gets downloaded
var file = window.URL.createObjectURL(new Blob(binaryData, {type: "application/pdf"}));
var fileURL = document.createElement("fileURL");
fileURL.href = file;
fileURL.download = serverResponse.name || fileName;
document.body.appendChild(fileURL);
fileURL.click();
//To remove the inserted element
window.onfocus = function () {
document.body.removeChild(fileURL)
}
关于javascript - Chrome 通过 Top-Frame Navigations 在网络重定向到新标签时阻止 PDF View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45599744/