最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - go to previous window automatically after printing dialog closes - Stack Overflow

programmeradmin1浏览0评论

I have a page where the html elements reside and print function is called via javascript at the end.

<script type="text/javascript">
$(document).ready(function(){
    window.print();
    window.history.back();
})
</script>

now I have this code to redirect user after print or if cancel is clicked. it works on local but in live server it goes to the previous page immediately.

I have a page where the html elements reside and print function is called via javascript at the end.

<script type="text/javascript">
$(document).ready(function(){
    window.print();
    window.history.back();
})
</script>

now I have this code to redirect user after print or if cancel is clicked. it works on local but in live server it goes to the previous page immediately.

Share Improve this question edited Sep 2, 2016 at 4:39 Regolith asked Aug 29, 2016 at 8:12 RegolithRegolith 2,98210 gold badges35 silver badges53 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Use this to go back to previous page

$(document).ready(function() {
   window.print();
   history.go(-1); 
});

or:

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

You could try with window.onafterprint function.

The afterprint event is raised after the user prints or aborts a print dialog.

Unfortunately, only works in FF & IE

So for your code (and only for FF & IE), I will try with something like:

<script type="text/javascript">
    $(document).ready(function(){
        window.print();
    })
    window.onafterprint = function() {
        history.go(-1);
    };
</script>

Now, for Webkit-based browser use matchMedia('print')...
Something like...

var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
    if (mql.matches) {
        console.log('onbeforeprint equivalent');
    } else {
        console.log('onafterprint equivalent');
    }
});

Source:
WindowEventHandlers.onafterprint
Detecting Print Requests with JavaScript
onbeforeprint and onafterprint is not working in Chrome and IE?

Maybe you should try print in a new window?

Something like this:

    var myWindow=window.open('','','width=200,height=100');
    myWindow.document.write("<p>This is 'myWindow'</p>");
    myWindow.document.close();
    myWindow.focus();
    myWindow.print();
    myWindow.close();
    myWindow.history.back();

Reference: JavaScript window.print() not working

(function() {
    window.print();
    setTimeout(() => {
        history.back(); 
    }, 500);
})();

This Will Work In All Browser This Will Get Back IN Previous Page When You Close Your Window window.print() This Will Execute Till Window Is Closed And After It Execute This Will Work Fine In All Browser

发布评论

评论列表(0)

  1. 暂无评论