Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

javascript - Printing a web page using just url and without opening new window?

<html>
<head>
<script type="text/javascript">
    var URL = "http://localhost:8000/foobar/";
    var W = window.open(URL);    **Note1**
    W.window.print(); 

</script>
</head>
<p> Print ME...............</p>
</html>

I am using this script to print a webpage. My views render this page and The JS take care all other things.

But I dont want to open new window for that. So, What should I use instead of window.open(URL) so no new window opens. Similarly, I don't want to open new window for print function.So, Whenever I render this page it do all stuff on the same page. No new window, No new tab. How can I achieve this. I google but nothing seems working.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this using a hidden iFrame (I'm using jquery for the example):

function loadOtherPage() {

    $("<iframe>")                             // create a new iframe element
        .hide()                               // make it invisible
        .attr("src", "/url/to/page/to/print") // point the iframe to the page you want to print
        .appendTo("body");                    // add iframe to the DOM to cause it to load the page

}

This will load the page you want to print. To print, you can add javascript code to the print page so that it gets printed after loading:

$(document).ready(function () {
    window.print();
});

This will print the page without showing a new window. I've tested this in IE8,9 and Google Chrome, so I'm not sure if this works for Safari or Firefox, though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...