javascript - 强制 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 时,它的行为方式是不需要的。我在测试时使用浏览器堆栈,结果好坏参半。
解决方案
推荐阅读
- sql-server - 需要帮助提取中间字符串
- angularjs - angularjs 将 ng-change 传递给孙子
- laravel - 使用 apiResource 向 Product 添加属性时,Laravel8 中的路由顺序正确吗?
- javascript - React/Javascript:将过滤器链接在一起
- mongodb - 将条件添加到最近的值结果
- reactjs - 如何在错误边界中获取 React 组件数据(当前状态、道具等)?
- java - 检查房间数据库android java中是否存在对象
- android - 使用带有颤振的android studio运行时应用程序未启动
- java - 天蓝色应用服务上的 Spring 应用中没有 UTF-8 编码
- git - pip install -e "private_repo" 导致错误,而 git clone "private_repo" 执行 OK