4

I want to open one word document using JavaScript as well as open print dialogue box for that opened document window.

Here is my code.

window.open('http://www.tizaq.com');

window.print();

It works, but the print dialogue gets opened for the current window, not the newly opened window. How do I do it?

2 Answers 2

13

Call print on the new window rather than the old:

var wnd = window.open('http://stackoverflow.com');
wnd.print();

I don't like your odds, though, of it not falling afoul of browser security. :-) The "external" window object may well not support print (window objects come in two types, the "external" type that other windows have access to, and the "internal" type that references itself, which has more permissions, etc.) At the least, you'll probably have to wait for the load event, but I best in general it's going to be tricky.

It seems to work for documents with the same origin, so the Same Origin Policy is a factor. That example crashes in IE6 (literally crashes the browser), but works for me in IE7 on Windows, and Chrome and Firefox 3.6 on Linux (and not in Opera 11 on Linux). Probably wouldn't hurt to put a delay / yield in there, e.g.:

var wnd = window.open(your_path_here);
setTimeout(function() {
    wnd.print();
}, 0);

You said "word document" in your question, but your example looks like a website. I have no idea whether this would work if you were opening a Microsoft Word document by loading it into a browser window.

Sign up to request clarification or add additional context in comments.

5 Comments

I'm trying the same thing but it isn't working for me in any browser. (Correction: It works in FF4 on Windows; doesn't in Chrome 10 and IE8)
@Pekka: Yeah, I think browser security is likely to kick in. And I for one probably want it to, although to be fair print on every platform I've used opens a dialog I can cancel, so it's not that evil. :-)
@Coder: I'm not terribly surprised, see the caveats. :-)
yes. I want to open word document only.. Just for example, here I put a website.
@Coder: Well, it may still work, if the document is being served from the same origin as the controlling page.
-1

Well, Better way

var my_window = window.open("", "mywindow1", "status=1,width=350,height=150");
my_window.document.write("<scr" + "ipt>window.location.href='http://stackoverflow.com';window.print();</scr" + "ipt>");

try Like this or better to make another page using iframe for print

1 Comment

Not a bad idea, although Window.Print(); will fail (it's window.print(), JavaScript is case sensitive). But have you actually made it work? When I try it, the printed result is blank. And I wonder if it would work with Word docs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.