简体   繁体   中英

$(window).resize() and Print Preview Mode

I have a very simple piece of code that refreshes window after resize.

$(window).resize(function() {
    location.reload();
});

When I try to open Print Preview Mode (Ctrl + P) in Chrome, it refreshes it as well. Any ideas how to avoid that behavior?

To determine print actions there are two events: beforeprint and afterprint . Using these event it's possible to set some flag in onbeforeprint that print activated and check this flag in resize handler.

window.onbeforeprint = function() {
    print = true;
};

Unfortunately Chrome doesn't support these events yet . As workaround in Chrome matchMedia may be used:

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

So solution for Chrome might be like this:

var print = false;
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
    if (mql.matches) {
        print = true;
    }
});

$(window).resize(function(event) {
  if (!print) {
    location.reload();
  }
});

After this print flag should be reset in onafterprint to allow further window resizes.

More info about this approach - http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM