首页 > 解决方案 > 在 chrome IOS 选项卡上打开 base64 pdf

问题描述

我正在生成一个 base64 pdf,我只需要在另一个 iOS chrome 选项卡中显示它。我有以下代码。

if (navigator.userAgent.includes('CriOS')) {
  var base64PDF = base64ArrayBuffer(response.data);
  var win = window.open();
  win.document.write('<iframe id="myIframe" width="600" height="315" src="data:application/pdf;base64,' + base64PDF + '" frameborder="0" allowfullscreen ></iframe>');
  win.document.write('<script>window.open(window.document.getElementById("myIframe").src) </script>');

} else if (navigator.userAgent.includes('iPad') || navigator.userAgent.includes('iPhone')) {
  var base64PDF = base64ArrayBuffer(response.data);
  window.location.assign('data:application/pdf;base64,' + base64PDF);
}

该代码让我在 iframe 上显示 pdf,但是当我这样做时,window.location.href 是生成 pdf 的 url,并且选项卡中的 url 是 about:blank。

所以我决定在文档中编写一个脚本,使用 iframe 的 src 执行 window.open ,但我在另一个选项卡中得到一个空页面。

我正在寻找在 chrome 选项卡的 url 中设置的 data:application/pdf;base64,..... 这将向用户显示“打开方式”选项,他将有类似的选项,通过 gmail 发送或邮件等。实际上我不能这样做,因为 url 是 about:blank 而不是有效的 PDF base64 链接。

我已经尝试过诸如 window.location、window.open、window.location.href、window.location.assign 之类的东西,以编程方式创建一个 a 标签并单击它以更改 href,然后打开 about:blank 选项卡就没有任何反应。

当我尝试时,类似于 window.location.href = 'data:application/pdf;base64,.....;return false;' , google chrome 重定向到一个新标签,url 正确,但返回 false;最后一部分或网址中的句子,以便执行错误的pdf。

我不知道为什么以编程方式无法打开该数据:应用程序.....但是如果您像我在本文开头提到的那样创建 iframe,然后用手指将 iframe 拖动到另一个选项卡上,chrome 打开数据:应用程序......在选项卡的 url 中。

标签: javascriptiosgoogle-chromepdf

解决方案


var divpdf = document.createElement('div');
divpdf.innerHTML = '<object  style="display:none;" id="docuFrame" type="application/pdf" width="1px" height="1px" data="' +
linkSource + '"></object>';
document.lastElementChild.appendChild(divpdf);
var frame = document.getElementById('docuFrame') as HTMLObjectElement;
window.open(frame.data);
frame.remove();
divpdf.remove();

推荐阅读