如何在没有弹出窗口阻止器的情况下将PDF下载到新标签页/窗口?

5

我有下面这个从服务器下载文件的服务调用。我目前已经设置PDF文件在新标签页/窗口中打开,其他类型的文档会被直接下载。

我现在遇到的问题是,由于浏览器弹出拦截器的限制,PDF文件无法打开。是否有什么解决方法?

  return formService.getForm(params)
        .$promise
        .then(response => {
            var blob = new Blob([response.data], {
                type: response.responseType
            });
            var fileUrl = (window.URL || window.webkitURL).createObjectURL(blob);
            if (response.responseType === 'application/pdf') {
                window.open(fileUrl);
            } else {
                var a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none"
                a.href = fileUrl;
                a.download = formName;
                a.target = "_blank";
                a.click();
                window.URL.revokeObjectURL(fileUrl);
            }
        })
        .catch(error => {
            console.error(`Error downloading form '${formName}' `, error);
        });

1
您正在强制执行点击事件,因此弹出窗口拦截器会建议这不是用户执行的操作。请让用户执行打开窗口的点击操作,然后再次测试。 - Mike
1个回答

15

我通过另一个stackoverflow的帖子找到了我的问题的答案。

window.open弹出窗口在单击事件期间被阻止

基本上,在进行服务调用之前,我调用var newWindow = window.open();,然后在成功回调中使用newWindow.location = fileUrl


非常好的解决方案,我通过添加超时来改善它以关闭新标签页:setTimeout(function(){ newWindow.close(); }, 500); (根据我的经验,如果没有超时,下载开始之前新标签页就已经被关闭了)。 - Pierre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接