【问题标题】:Open PDF blob file in new browser tab with custom tile using Javascript使用 Javascript 在新的浏览器选项卡中使用自定义磁贴打开 PDF blob 文件
【发布时间】:2020-11-04 23:28:31
【问题描述】:

我正在尝试使用 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


    【解决方案1】:

    这样的工作:

    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>`)
    

    【讨论】:

    • 这太棒了,我还在 iframe 之前添加了一些样式来去除新标签的粗丑边框:&lt;style&gt;body {margin: 0 !important;}&lt;/style&gt;
    猜你喜欢
    • 2016-05-04
    • 2021-03-25
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2014-03-19
    相关资源
    最近更新 更多