JavaScript 打印的窗口标题

Window title for javascript print

本文关键字:窗口标题 打印 JavaScript      更新时间:2023-09-26

找到这段代码来打印我修改的javascript元素。 尽管我添加了document.title<title></title>标签,但在常规文本编辑器中打开的窗口显示 untitled .

这通常是保存文本之前的情况。 无论如何,有没有办法显示标题?

    var element=document.getElementById(element_id);
    var newWin=window.open('','Print-Window','width=400,height=400,top=100,left=100');
    newWin.document.open();
    newWin.document.title = "Readings on PageLinks";
    newWin.document.write('<html><head><title>'+newWin.document.title+'</title></head><body   onload="window.print()">'+element.innerHTML+'</body></html>');
    newWin.document.close();
    setTimeout(function(){ newWin.close(); },10);

实际上原始代码也对我有用(Chrome,没有在其他浏览器上测试)

var element_id = "id1";
var element = document.getElementById(element_id);
var newWin = window.open('', 'Print-Window', 'width=400,height=400,top=100,left=100');
newWin.document.open();
newWin.document.title = "Readings on PageLinks";
newWin.document.write('<html><head></head><body onload="window.print()">' + element.innerHTML + '</body></html>');
newWin.document.close();
setTimeout(function() {
    newWin.close();
}, 10);​

请参阅JSFiddle上

我的猜测是分配newWin.document.title = "Readings on PageLinks";失败,因为当时页面中没有<title>元素。

因此,newWin.document.title仍然没有定义。然后你把它连接到字符串<title>'+newWin.document.title+'</title>,所以它被toString()-ed为"undefined"。

因此,只需将标题直接写入字符串即可

newWin.document.write('<html><head><title>Readings on PageLinks</title>...');

正如Eran Medan在评论中建议的那样。

这对我有用。

这可能是随文档打开的编辑器的行为。 在保存文档之前,编辑器标题将显示"无标题"。 这一定是设计使然。