首页 文章

在Chrome中打开blob objectURL

提问于
浏览
16

我想在javascript中使用 window.open(fileObjectURL) 在Chrome浏览器(Chrome 56.0.2924.87,Ubuntu 14.04)的新标签页中打开PDF . 我正在从base64编码数据创建blob并创建一个这样的objectURL:

const fileObjectURL = URL.createObjectURL(fileBlob);

它在最新的Firefox浏览器中运行良好 . 但在Chrome中,我可以看到新标签已打开,但随后立即关闭 . 所以我在控制台中没有出现任何错误等 . 它现在在Chrome中运行的唯一方法是将base64数据直接提供给 window.open(fileBase64Data) 函数 . 但我不喜欢在网址中设置的完整数据 .

也许这是Chrome阻止blob打开的安全问题?

2 回答

  • 3

    原因可能是adblock扩展(我有完全相同的问题) .

  • 45

    在将blob url放入窗口之前必须打开新窗口:

    let newWindow = window.open('/')

    您还可以使用其他页面,如 /loading ,带有加载指示器 .

    然后你需要等待newWindow加载,你可以在这个窗口中推送你的blob文件的url:

    newWindow.onload = () => {
        newWindow.location = URL.createObjectURL(blob);
    };
    

    Adblock扩展程序不会阻止它 .

    我正在使用AJAX和ES生成器,如下所示:

    let openPDF = openFile();
    openPDF.next();
    axios.get('/pdf', params).then(file => {
      openPDF.next(file);
    });
    
    function* openFile() {
      let newWindow = window.open('/pages/loading');
      // get file after .next(file)
      let file = yield;
      // AJAX query can finish before window loaded,
      // So we need to check document.readyState, else listen event
      if (newWindow.document.readyState === 'complete') {
        openFileHelper(newWindow, file);
      } else {
        newWindow.onload = () => {
          openFileHelper(newWindow, file);
        };
      }
    }
    
    function openFileHelper(newWindow, file) {
      let blob = new Blob([file._data], {type: `${file._data.type}`});
      newWindow.location = URL.createObjectURL(blob);
    }
    

相关问题