首页 > 解决方案 > 在新的浏览器选项卡中使用 Javascript 使用自定义磁贴打开 PDF blob 文件

问题描述

我正在尝试使用 Javascript 在新选项卡中打开 PDF 文件。它工作正常,除了标签标题。选项卡标题显示一些随机 GUID。我用的是浏览器 Chrome。

代码:

var myBlob= new Blob([blob], {type: ‘application/pdf’})
var file = new File([myBlob], "fileName.pdf");
const data = window.URL.createObjectURL(myBlob)
window.open(data)// it is opening the pdf in new tab but tab name is random GUID

所以我有不同的方法:

  1. // it is opening the pdf in new tab but tab name is random GUID`
    window.open(data,"my custom tab name") 
    
  2. // still no luck`
    window.open(data,"my custom tab name").document.title = "New Page Title!";
    
  3. // Still not working
    var newWindow = window.open(data,'_blank');  
    setTimeout(function () {
        newWindow.document.title = "My Tab Name";
    }, 100);
    
  4. // still not working
    var newWindow = window.open(data, "_blank");
    newWindow.addEventListener('load', function() {
        newWindow.document.title = 'New Title';
    });
    
  5. // downloading file not showing in new tab
    var a = document.createElement('A');
    a.href = data;
    a.download = data;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a); 
    

所以用了所有的方法。我可以在新标签中显示 PDF,但我无法设置标签标题。

谁可以帮我这个事 ?

标签: javascript

解决方案


像这样的工作:

const newWindow = window.open()
newWindow.document.title = 'My Tab Name'
newWindow.document.write`<iframe src="${URL.createObjectURL(myBlob)}" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>`)

推荐阅读