简体   繁体   English

我该如何编辑 <head> 当我使用window.open打开一个新窗口时

[英]How do I edit the <head> when i am opening a new window using window.open

I am trying to open a new window and pass in some generated html for a report that I am making. 我正在尝试打开一个新窗口,并为我正在生成的报告传递一些生成的html。

I have stripped down my source code but the following is a working example of my problem. 我已经精简了源代码,但是以下是我的问题的有效示例。

    var windowUrl = "/";
    var uniqueName = new Date();
    var windowName = "Print" + uniqueName.getTime();
    var printWindow = window.open(
        windowUrl,
        windowName,
        "left=0,top=0,width=500,height=500"
    );

    var link = printWindow.document.createElement('link');
    link.rel = 'stylesheet';
    link.href = '//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css';
    printWindow.document.head.appendChild(link);
    printWindow.document.write('<div><section id="divToPrint"><div class="container page-sub">');
    printWindow.document.write('<p>Hello World</p>');
    printWindow.document.write('</div></section></div>');
    printWindow.document.close();
    printWindow.focus();

The write method works great, I am able to write my code I need to the DOM but it only writes to the body. write方法的效果很好,我能够将所需的代码写入DOM,但它只会写入正文。 Now I need to add information into the head such as styles, title etc... but I am unable to get my head code into the head tag. 现在,我需要在标题中添加样式,标题等信息,但是我无法将我的标题代码添加到head标签中。

Is it even possible to write the head of the new window? 甚至可以写下新窗口的标题吗? when it outputs the head tag looks like this even after adding the link. 即使在添加链接后,输出head标记时也是如此。

<head></head>

I don't know if it is relevant but I am using ReactJS. 我不知道它是否相关,但是我正在使用ReactJS。 Maybe there is some sort of alternative. 也许有其他选择。

You can access the head node of the window, then use some native JavaScript DOM APIs: 您可以访问窗口的head节点,然后使用一些本机JavaScript DOM API:

var link = printWindow.document.createElement('link');
link.href = 'whatever';
printWindow.head.appendChild(link);

Updated example based on your code: 根据您的代码更新了示例:

var windowUrl = "/";
var uniqueName = new Date();
var windowName = "Print" + uniqueName.getTime();
var printWindow = window.open(
    windowUrl,
    windowName,
    "left=0,top=0,width=500,height=500"
);

printWindow.document.write('<div><section id="divToPrint"><div class="container page-sub">');
printWindow.document.write('<p>Hello World</p>');
printWindow.document.write('</div></section></div>');
printWindow.document.close();
printWindow.focus();
var link = printWindow.document.createElement('link');
link.rel = 'stylesheet';
link.href = '//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css';
printWindow.document.head.appendChild(link);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM