user823527
user823527

Reputation: 3712

Window title for javascript print

Found this code to print a javascript element that I modified. Although I added the document.title and the <title></title> tags, the window that opens in the regular text editor says untitled.

This is usually the situation before the text is saved. Is there a way to show a title anyway?

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

Upvotes: 5

Views: 7998

Answers (3)

user823527
user823527

Reputation: 3712

It could be a behavior of the editor that's opened with the document. Until the document is saved, the editor header will say "untitled". This must be by design.

Upvotes: 0

Eran Medan
Eran Medan

Reputation: 45765

Actually the original code worked for me as well (Chrome, didn't test on other browsers)

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);​

See on JSFiddle

Upvotes: 3

Imp
Imp

Reputation: 8609

My guess is that the assignment newWin.document.title = "Readings on PageLinks"; failed, because there was no <title> element in the page at that time.

Thus, newWin.document.title was still undefined. Then you concatenated it to the string <title>'+newWin.document.title+'</title>, so it got toString()-ed as "undefined".

So, just write the title directly into the string

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

as Eran Medan suggested in the comments.

This worked for me.

Upvotes: 1

Related Questions