javascript - Chrome 通过 Top-Frame Navigations 在网络重定向到新标签时阻止 PDF View

标签 javascript angularjs google-chrome pdf iframe

根据 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数据失败,如下所示

enter image description here

<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/

相关文章:

javascript - 为什么 Google Chrome 找不到我的 app.js 文件

jquery - 边框半径不适用于 chrome 中的相对定位图像

javascript - 如果从 SVG 内的 &lt;![CDATA[] > 脚本标记中的 javascript 应用,Chrome 不会渲染旋转

javascript - 粘性导航在滚动完成之前不会粘性

javascript - 还有比redirect()和render()更好的函数吗? 【 Node 应用】

javascript - 当发布和订阅位于两个单独的文件中时,Amplify.js 发布订阅不起作用

javascript - 使用 AngularJS 中的表单对 ControllerAs 进行单元测试

javascript - 如何在注册后(即从控制台)执行 Angular Controller 的构造函数?

javascript - 错误 : Cannot find module 'entities/lib/decode_codepoint.js'

javascript - ES6 map 垫片如何工作