首页 > 解决方案 > 强制 Ipad 下载 pdf 并在新标签页中打开

问题描述

我有一个 utils 函数,我正在利用它在用户浏览器上创建下载。单击相关元素时会提示用户下载文件,此时我们会进行后端调用以创建相关链接。有问题的问题是 ipad 用户没有被提示下载文件,而是在当前选项卡中打开文件,这破坏了用户体验。以下代码用于模拟下载

const showFile = (blob, fileName) => {
  // It is necessary to create a new blob object with mime-type explicitly set
  // otherwise only Chrome works like it should
  var newBlob = new Blob([blob], { type: "application/pdf" });

  // IE doesn't allow using a blob object directly as link href
  // instead it is necessary to use msSaveOrOpenBlob
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(newBlob);
    return;
  }

  // For other browsers:
  // Create a link pointing to the ObjectURL containing the blob.
  const data = window.URL.createObjectURL(newBlob);
  var link = document.createElement("a");
  link.href = data;
  link.download = fileName;
  link.click();
  setTimeout(function() {
    // For Firefox it is necessary to delay revoking the ObjectURL
    window.URL.revokeObjectURL(data);
  }, 100);
};

export const prepareFileName = fileName => fileName.replace(/\./g, " ");

export default showFile;

我试图以target="_blank"几种不同的方式(例如link.setAttribute('target', '_blank'))添加,但没有成功。需要明确的是,上面的代码在 chrome 和 Edge 上运行没有问题,但是当涉及到 ipad 时,它的行为方式是不需要的。我在测试时使用浏览器堆栈,结果好坏参半。

标签: javascriptvue.js

解决方案


推荐阅读