Firefox在更改URL后立即以编程方式打开选项卡

时间:2018-04-02 14:20:08

标签: javascript firefox browser

我正在尝试下载PDF文件(需要Bearer令牌,因此我不能只使用给定的URL打开新标签页),然后在新标签页中打开它。除了Firefox之外,我已经在每个浏览器中都能使用它。在Firefox中,选项卡打开,但在尝试导航到blob URL时,选项卡将关闭。如果我手动将blob URL复制并粘贴到新选项卡中,则会正确加载PDF。

以下是我使用的代码(美元符号来自Angular 1):

showReceipt: function(receiptUrl) {
    var windowReference;
    if (!($window.navigator && $window.navigator.msSaveOrOpenBlob)) {
        // This is the workaround for Safari: https://stackoverflow.com/a/39387533/2595915
        // It also works in Chrome, but not in IE and Edge
        // We open the new window in an if block to avoid opening a useless blank tab in IE/Edge
        windowReference = $window.open();
    }
    api.request('GET', receiptUrl, {}, {}, { useUrl: true, successHandler: api.blobSuccessHandler, responseType: 'blob' }).then(
        function (blob) {
            // 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 and Edge don'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;
            }

            var data = $window.URL.createObjectURL(newBlob);
            windowReference.location.href = data; // Causes the tab to close
            console.log(data); // Copy and pasting this URL works, assuming I comment out the revoke command below
            $timeout(function () {
                $window.URL.revokeObjectURL(data);
            }, 100);
        }
    );
}

我还尝试过以编程方式创建临时a元素并单击该元素,然后我得到相同的结果(在Firefox中立即关闭标签,在Chrome中正常工作)。

0 个答案:

没有答案