Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Determine If Print/Cancel Button in Google Chrome's Print Preview is Clicked

I've been printing my page using the code below:

window.print();

An image below is what the print preview in Google chrome browser looks like. It has two main buttons: print and cancel.

enter image description here

I want to know if the user has clicked the print or cancel buttons. What I did uses jquery:

HTML Code of the Print Preview:

<button class="print default" i18n-content="printButton">Print</button>
<button class="cancel" i18n-content="cancel">Cancel</button>

Jquery Code:

 $('button > .cancel').click(function (e) {                
      alert('Cancel');
 });

 $('button > .print').click(function (e) {                
      alert('Print');
 });

I tried the code above with no luck. What am I missing?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can not access Chrome's internal windows (printing dialog in this case) directly from a regular web page.

    (function () {

        var beforePrint = function () {
            alert('Functionality to run before printing.');
        };

        var afterPrint = function () {
            alert('Functionality to run after printing');
        };

        if (window.matchMedia) {
            var mediaQueryList = window.matchMedia('print');

            mediaQueryList.addListener(function (mql) {
                //alert($(mediaQueryList).html());
                if (mql.matches) {
                    beforePrint();
                } else {
                    afterPrint();
                }
            });
        }

        window.onbeforeprint = beforePrint;
        window.onafterprint = afterPrint;

    }());

Or, If you want to do something when the print preview gets opened, you can try below:

$(document).bind("keyup keydown", function (e) {
         if (e.ctrlKey && e.keyCode == 80) {
             setTimeout(function () { CallAfterWindowLoad();}, 5000);
             return true;
         }
     });

    function CallAfterWindowLoad()
    {
        alert("Open and call");
    }

Reference: How to capture the click event on the default print menu called by Javascript window.print()

Maybe if you provide your requirements for this two buttons click event, we can provide you an alternate solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...