Related
I want to capture the browser window/tab close event.
I have tried the following with jQuery:
jQuery(window).bind(
"beforeunload",
function() {
return confirm("Do you really want to close?")
}
)
But it works on form submission as well, which is not what I want. I want an event that triggers only when the user closes the window.
The beforeunload event fires whenever the user leaves your page for any reason.
For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.
You could exclude form submissions and hyperlinks (except from other frames) with the following code:
var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });
$(window).on("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
For jQuery versions older than 1.7, try this:
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
The live method doesn't work with the submit event, so if you add a new form, you'll need to bind the handler to it as well.
Note that if a different event handler cancels the submit or navigation, you will lose the confirmation prompt if the window is actually closed later. You could fix that by recording the time in the submit and click events, and checking if the beforeunload happens more than a couple of seconds later.
Maybe just unbind the beforeunload event handler within the form's submit event handler:
jQuery('form').submit(function() {
jQuery(window).unbind("beforeunload");
...
});
For a cross-browser solution (tested in Chrome 21, IE9, FF15), consider using the following code, which is a slightly tweaked version of Slaks' code:
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (! inFormOrLink) {
returnValue = "Do you really want to close?";
}
eventObject.returnValue = returnValue;
return returnValue;
});
Note that since Firefox 4, the message "Do you really want to close?" is not displayed. FF just displays a generic message. See note in https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
window.onbeforeunload = function () {
return "Do you really want to close?";
};
My answer is aimed at providing simple benchmarks.
HOW TO
See #SLaks answer.
$(window).on("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
How long does the browser take to finally shut your page down?
Whenever an user closes the page (x button or CTRL + W), the browser executes the given beforeunload code, but not indefinitely. The only exception is the confirmation box (return 'Do you really want to close?) which will wait until for the user's response.
Chrome: 2 seconds.
Firefox: ∞ (or double click, or force on close)
Edge: ∞ (or double click)
Explorer 11: 0 seconds.
Safari: TODO
What we used to test this out:
A Node.js Express server with requests log
The following short HTML file
What it does is to send as many requests as it can before the browser shut downs its page (synchronously).
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function request() {
return $.ajax({
type: "GET",
url: "http://localhost:3030/" + Date.now(),
async: true
}).responseText;
}
window.onbeforeunload = () => {
while (true) {
request();
}
return null;
}
</script>
</body>
</html>
Chrome output:
GET /1480451321041 404 0.389 ms - 32
GET /1480451321052 404 0.219 ms - 32
...
GET /hello/1480451322998 404 0.328 ms - 32
1957ms ≈ 2 seconds // we assume it's 2 seconds since requests can take few milliseconds to be sent.
For a solution that worked well with third party controls like Telerik (ex.: RadComboBox) and DevExpress that use the Anchor tags for various reasons, consider using the following code, which is a slightly tweaked version of desm's code with a better selector for self targeting anchor tags:
var inFormOrLink;
$('a[href]:not([target]), a[href][target=_self]').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (! inFormOrLink) {
returnValue = "Do you really want to close?";
}
eventObject.returnValue = returnValue;
return returnValue;
});
I used Slaks answer but that wasn't working as is, since the onbeforeunload returnValue is parsed as a string and then displayed in the confirmations box of the browser. So the value true was displayed, like "true".
Just using return worked.
Here is my code
var preventUnloadPrompt;
var messageBeforeUnload = "my message here - Are you sure you want to leave this page?";
//var redirectAfterPrompt = "http://www.google.co.in";
$('a').live('click', function() { preventUnloadPrompt = true; });
$('form').live('submit', function() { preventUnloadPrompt = true; });
$(window).bind("beforeunload", function(e) {
var rval;
if(preventUnloadPrompt) {
return;
} else {
//location.replace(redirectAfterPrompt);
return messageBeforeUnload;
}
return rval;
})
Perhaps you could handle OnSubmit and set a flag that you later check in your OnBeforeUnload handler.
Unfortunately, whether it is a reload, new page redirect, or browser close the event will be triggered. An alternative is catch the id triggering the event and if it is form dont trigger any function and if it is not the id of the form then do what you want to do when the page closes. I am not sure if that is also possible directly and is tedious.
You can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
/* Do you small action code here */
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload
jQuery(window).bind("beforeunload", function (e) {
var activeElementTagName = e.target.activeElement.tagName;
if (activeElementTagName != "A" && activeElementTagName != "INPUT") {
return "Do you really want to close?";
}
})
If your form submission takes them to another page (as I assume it does, hence the triggering of beforeunload), you could try to change your form submission to an ajax call. This way, they won't leave your page when they submit the form and you can use your beforeunload binding code as you wish.
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()
$(window).bind("beforeunload", function() {
return true || confirm("Do you really want to close?");
});
on complete or link
$(window).unbind();
Try this also
window.onbeforeunload = function ()
{
if (pasteEditorChange) {
var btn = confirm('Do You Want to Save the Changess?');
if(btn === true ){
SavetoEdit();//your function call
}
else{
windowClose();//your function call
}
} else {
windowClose();//your function call
}
};
My Issue: The 'onbeforeunload' event would only be triggered if there were odd number of submits(clicks). I had a combination of solutions from similar threads in SO to have my solution work. well my code will speak.
<!--The definition of event and initializing the trigger flag--->
$(document).ready(function() {
updatefgallowPrompt(true);
window.onbeforeunload = WarnUser;
}
function WarnUser() {
var allowPrompt = getfgallowPrompt();
if(allowPrompt) {
saveIndexedDataAlert();
return null;
} else {
updatefgallowPrompt(true);
event.stopPropagation
}
}
<!--The method responsible for deciding weather the unload event is triggered from submit or not--->
function saveIndexedDataAlert() {
var allowPrompt = getfgallowPrompt();
var lenIndexedDocs = parseInt($('#sortable3 > li').size()) + parseInt($('#sortable3 > ul').size());
if(allowPrompt && $.trim(lenIndexedDocs) > 0) {
event.returnValue = "Your message";
} else {
event.returnValue = " ";
updatefgallowPrompt(true);
}
}
<!---Function responsible to reset the trigger flag---->
$(document).click(function(event) {
$('a').live('click', function() { updatefgallowPrompt(false); });
});
<!--getter and setter for the flag---->
function updatefgallowPrompt (allowPrompt){ //exit msg dfds
$('body').data('allowPrompt', allowPrompt);
}
function getfgallowPrompt(){
return $('body').data('allowPrompt');
}
Just verify...
function wopen_close(){
var w = window.open($url, '_blank', 'width=600, height=400, scrollbars=no, status=no, resizable=no, screenx=0, screeny=0');
w.onunload = function(){
if (window.closed) {
alert("window closed");
}else{
alert("just refreshed");
}
}
}
var validNavigation = false;
jQuery(document).ready(function () {
wireUpEvents();
});
function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}
function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function () {
debugger
if (!validNavigation) {
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function (e) {
debugger
if (e.keyCode == 116) {
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function () {
debugger
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function () {
debugger
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function () {
debugger
validNavigation = true;
});
}`enter code here`
Following worked for me;
$(window).unload(function(event) {
if(event.clientY < 0) {
//do whatever you want when closing the window..
}
});
Is there any way in JavaScript/JQuery to detect that a user has left the tab/web browser app and returned on Mobile?
On Desktop it's pretty simple with JQuery and 'mouseleave' type functions, but I can't figure out a solution for mobile.
Have you tried the focus and blur event on your window? This should work in all modern browsers including mobile ones.
var focused = true;
window.onfocus = function() {
focused = true;
};
window.onblur = function() {
focused = false;
};
What about comparing time and timeout (halted at leaving)?:
function isleaving(callback){
function check(val){
var time=new Date().getTime() / 1000;
val=val||time;
if(val==time){
//All ok so keep checking
setTimeout(function(){check(time+1);},1000);
}else{
callback();
}
}
check();
}
In my application, I tried to print out a voucher page for the user like this:
var htm ="<div>Voucher Details</div>";
$('#divprint').html(htm);
window.setTimeout('window.print()',2000);
'divprint' is a div in my page which store information about the voucher.
It works, and the print page pops up. But I want to advance the application once the user clicks 'print' or 'close' in the browser's pop-up print dialog.
For example, I'd like to redirect user to another page after pop up window is closed:
window.application.directtoantherpage();//a function which direct user to other page
How can I determine when the pop up print window is closed or print is finished?
You can listen to the afterprint event.
https://developer.mozilla.org/en-US/docs/Web/API/window.onafterprint
window.onafterprint = function(){
console.log("Printing completed...");
}
It may be possible to use window.matchMedia to get this functionality in another way.
(function() {
var beforePrint = function() {
console.log('Functionality to run before printing.');
};
var afterPrint = function() {
console.log('Functionality to run after printing');
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
Source: http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/
On chrome (V.35.0.1916.153 m) Try this:
function loadPrint() {
window.print();
setTimeout(function () { window.close(); }, 100);
}
Works great for me. It will close window after user finished working on printing dialog.
compatible with chrome, firefox, opera, Internet Explorer
Note: jQuery required.
<script>
window.onafterprint = function(e){
$(window).off('mousemove', window.onafterprint);
console.log('Print Dialog Closed..');
};
window.print();
setTimeout(function(){
$(window).one('mousemove', window.onafterprint);
}, 1);
</script>
See https://stackoverflow.com/a/15662720/687315. As a workaround, you can listen for the afterPrint event on the window (Firefox and IE) and listen for mouse movement on the document (indicating that the user has closed the print dialog and returned to the page) after the window.mediaMatch API indicates that the media no longer matches "print" (Firefox and Chrome).
Keep in mind that the user may or may not have actually printed the document. Also, if you call window.print() too often in Chrome, the user may not have even been prompted to print.
window.print behaves synchronously on chrome .. try this in your console
window.print();
console.log("printed");
"printed" doesn't display unless the print dialog is closed(canceled/saved/printed) by the user.
Here is a more detailed explanation about this issue.
I am not sure about IE or Firefox will check and update that later
You can detect when window.print() is finished simply by putting it in another function
//function to call if you want to print
var onPrintFinished=function(printed){console.log("do something...");}
//print command
onPrintFinished(window.print());
tested in Firefox,Google chrome,IE
This Actually worked for me in chrome. I was pretty suprised.
jQuery(document).bind("keyup keydown", function(e){
if(e.ctrlKey && e.keyCode == 80){
Print(); e.preventDefault();
}
});
Where Print is a function I wrote that calls window.print(); It also works as a pure blocker if you disable Print();
As noted here by user3017502
window.print() will pause so you can add an onPrintFinish or onPrintBegin like this
function Print(){
onPrintBegin
window.print();
onPrintFinish();
}
Tested IE, FF, Chrome and works in all.
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
Given that you wish to wait for the print dialog to go away I would use focus binding on the window.
print();
var handler = function(){
//unbind task();
$(window).unbind("focus",handler);
}
$(window).bind("focus",handler);
By putting in the unbind in the handler function we prevent the focus event staying bond to the window.
Simplest way to detect if print has finished and close print window:
window.onafterprint = function(){
window.onfocus = function(){
window.close();
}
};
Print in new window with w = window.open(url, '_blank') and try w.focus();w.close(); and detect when page is closed. Works in all browsers.
w = window.open(url, '_blank');
w.onunload = function(){
console.log('closed!');
}
w.focus();
w.print();
w.close();
Window close after finish print.
It works for me with $(window).focus().
var w;
var src = 'http://pagetoprint';
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
w = $('<iframe></iframe>');
w.attr('src', src);
w.css('display', 'none');
$('body').append(w);
w.load(function() {
w[0].focus();
w[0].contentWindow.print();
});
$(window).focus(function() {
console.log('After print');
});
}
else {
w = window.open(src);
$(w).unload(function() {
console.log('After print');
});
}
I think the window focus approach is the correct one. Here is an example in which I wanted to open a PDF url blob in a hidden iframe and print it. After printed or canceled, I wanted to remove the iframe.
/**
* printBlob will create if not exists an iframe to load
* the pdf. Once the window is loaded, the PDF is printed.
* It then creates a one-time event to remove the iframe from
* the window.
* #param {string} src Blob or any printable url.
*/
export const printBlob = (src) => {
if (typeof window === 'undefined') {
throw new Error('You cannot print url without defined window.');
}
const iframeId = 'pdf-print-iframe';
let iframe = document.getElementById(iframeId);
if (!iframe) {
iframe = document.createElement('iframe');
iframe.setAttribute('id', iframeId);
iframe.setAttribute('style', 'position:absolute;left:-9999px');
document.body.append(iframe);
}
iframe.setAttribute('src', src);
iframe.addEventListener('load', () => {
iframe.contentWindow.focus();
iframe.contentWindow.print();
const infanticide = () => {
iframe.parentElement.removeChild(iframe);
window.removeEventListener('focus', infanticide);
}
window.addEventListener('focus', infanticide);
});
};
It is difficult, due to different browser behavior after print. Desktop Chrome handles the print dialogue internally, so doesn't shift focus after print, however, afterprint event works fine here (As of now, 81.0). On the other hand, Chrome on mobile device and most of the other browsers shifts focus after print and afterprint event doesn't work consistently here. Mouse movement event doesn't work on mobile devices.
So, Detect if it is Desktop Chrome,
If Yes, use afterprint event. If No, use focus based detection. You can also use mouse movement event(Works in desktop only) in combination of these, to cover more browsers and more scenarios.
well, just to remind everyone that the afterprint will not determine the print action button instead it will execute whenever the print window is closed or closing, both cancel button or esc key which closing the print window will consider afterprint while there is no actual print happening yet.
Implementing window.onbeforeprint and window.onafterprint
The window.close() call after the window.print() is not working in Chrome v 78.0.3904.70
To approach this I'm using Adam's answer with a simple modification:
function print() {
(function () {
let afterPrintCounter = !!window.chrome ? 0 : 1;
let beforePrintCounter = !!window.chrome ? 0 : 1;
var beforePrint = function () {
beforePrintCounter++;
if (beforePrintCounter === 2) {
console.log('Functionality to run before printing.');
}
};
var afterPrint = function () {
afterPrintCounter++;
if (afterPrintCounter === 2) {
console.log('Functionality to run after printing.');
//window.close();
}
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
//window.print(); //To print the page when it is loaded
}
I'm calling it in here:
<body onload="print();">
This works for me.
Note that I use a counter for both functions, so that I can handle this event in different browsers (fires twice in Chrome, and one time in Mozilla).
For detecting the browser you can refer to this answer
I want to track clicks on AdSense elements on my page. To achieve that I put the focus on the window object and if it loses focus, I check if the mouse was in the area of the AdSense iFrame. Then i put the focus back on the window again.
This works. But in Chrome it works only once. So if I click on an adSense ad (opening in a new tab) and then I click on another one, the event doesn't fire anymore.
If I execute $(window).focus() in the console, the onBlur event fires again - but the $(window).focus() executed from within my code doesn't show any effect. I tried it with a Timeout too, without success.
Any ideas?
trackElements("#contentAdSense, #fallbackAdSense, #sidebarAdSense");
function trackElements (elementsToTrack)
{
var isOverElement = false;
$(window).focus();
$(elementsToTrack).mouseenter(function(e){
isOverElement = e.currentTarget.id;
});
$(elementsToTrack).mouseleave(function(e){
isOverElement = false;
});
$(window).blur(function(e){
windowLostBlur();
});
function windowLostBlur ()
{
if (isOverElement)
{
console.log(isOverElement);
$(window).focus();
}
};
};
Simplified version: https://jsfiddle.net/327skdns/2/
This is a documented Chrome bug: jQuery focus not working in Chrome
You need to wrap your focus() call with a setTimeout:
trackElements("#contentAdSense, #fallbackAdSense, #sidebarAdSense");
function trackElements (elementsToTrack)
{
var isOverElement = false;
$(window).focus();
$(elementsToTrack).mouseenter(function(e){
isOverElement = e.currentTarget.id;
});
$(elementsToTrack).mouseleave(function(e){
isOverElement = false;
});
$(window).blur(function(e){
windowLostBlur();
});
function windowLostBlur ()
{
if (isOverElement)
{
console.log(isOverElement);
setTimeout( function(){ $(window).focus(); }, 50 );
}
};
}
In my application, I tried to print out a voucher page for the user like this:
var htm ="<div>Voucher Details</div>";
$('#divprint').html(htm);
window.setTimeout('window.print()',2000);
'divprint' is a div in my page which store information about the voucher.
It works, and the print page pops up. But I want to advance the application once the user clicks 'print' or 'close' in the browser's pop-up print dialog.
For example, I'd like to redirect user to another page after pop up window is closed:
window.application.directtoantherpage();//a function which direct user to other page
How can I determine when the pop up print window is closed or print is finished?
You can listen to the afterprint event.
https://developer.mozilla.org/en-US/docs/Web/API/window.onafterprint
window.onafterprint = function(){
console.log("Printing completed...");
}
It may be possible to use window.matchMedia to get this functionality in another way.
(function() {
var beforePrint = function() {
console.log('Functionality to run before printing.');
};
var afterPrint = function() {
console.log('Functionality to run after printing');
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
Source: http://tjvantoll.com/2012/06/15/detecting-print-requests-with-javascript/
On chrome (V.35.0.1916.153 m) Try this:
function loadPrint() {
window.print();
setTimeout(function () { window.close(); }, 100);
}
Works great for me. It will close window after user finished working on printing dialog.
compatible with chrome, firefox, opera, Internet Explorer
Note: jQuery required.
<script>
window.onafterprint = function(e){
$(window).off('mousemove', window.onafterprint);
console.log('Print Dialog Closed..');
};
window.print();
setTimeout(function(){
$(window).one('mousemove', window.onafterprint);
}, 1);
</script>
See https://stackoverflow.com/a/15662720/687315. As a workaround, you can listen for the afterPrint event on the window (Firefox and IE) and listen for mouse movement on the document (indicating that the user has closed the print dialog and returned to the page) after the window.mediaMatch API indicates that the media no longer matches "print" (Firefox and Chrome).
Keep in mind that the user may or may not have actually printed the document. Also, if you call window.print() too often in Chrome, the user may not have even been prompted to print.
window.print behaves synchronously on chrome .. try this in your console
window.print();
console.log("printed");
"printed" doesn't display unless the print dialog is closed(canceled/saved/printed) by the user.
Here is a more detailed explanation about this issue.
I am not sure about IE or Firefox will check and update that later
You can detect when window.print() is finished simply by putting it in another function
//function to call if you want to print
var onPrintFinished=function(printed){console.log("do something...");}
//print command
onPrintFinished(window.print());
tested in Firefox,Google chrome,IE
This Actually worked for me in chrome. I was pretty suprised.
jQuery(document).bind("keyup keydown", function(e){
if(e.ctrlKey && e.keyCode == 80){
Print(); e.preventDefault();
}
});
Where Print is a function I wrote that calls window.print(); It also works as a pure blocker if you disable Print();
As noted here by user3017502
window.print() will pause so you can add an onPrintFinish or onPrintBegin like this
function Print(){
onPrintBegin
window.print();
onPrintFinish();
}
Tested IE, FF, Chrome and works in all.
setTimeout(function () { window.print(); }, 500);
window.onfocus = function () { setTimeout(function () { window.close(); }, 500); }
Given that you wish to wait for the print dialog to go away I would use focus binding on the window.
print();
var handler = function(){
//unbind task();
$(window).unbind("focus",handler);
}
$(window).bind("focus",handler);
By putting in the unbind in the handler function we prevent the focus event staying bond to the window.
Simplest way to detect if print has finished and close print window:
window.onafterprint = function(){
window.onfocus = function(){
window.close();
}
};
Print in new window with w = window.open(url, '_blank') and try w.focus();w.close(); and detect when page is closed. Works in all browsers.
w = window.open(url, '_blank');
w.onunload = function(){
console.log('closed!');
}
w.focus();
w.print();
w.close();
Window close after finish print.
It works for me with $(window).focus().
var w;
var src = 'http://pagetoprint';
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
w = $('<iframe></iframe>');
w.attr('src', src);
w.css('display', 'none');
$('body').append(w);
w.load(function() {
w[0].focus();
w[0].contentWindow.print();
});
$(window).focus(function() {
console.log('After print');
});
}
else {
w = window.open(src);
$(w).unload(function() {
console.log('After print');
});
}
I think the window focus approach is the correct one. Here is an example in which I wanted to open a PDF url blob in a hidden iframe and print it. After printed or canceled, I wanted to remove the iframe.
/**
* printBlob will create if not exists an iframe to load
* the pdf. Once the window is loaded, the PDF is printed.
* It then creates a one-time event to remove the iframe from
* the window.
* #param {string} src Blob or any printable url.
*/
export const printBlob = (src) => {
if (typeof window === 'undefined') {
throw new Error('You cannot print url without defined window.');
}
const iframeId = 'pdf-print-iframe';
let iframe = document.getElementById(iframeId);
if (!iframe) {
iframe = document.createElement('iframe');
iframe.setAttribute('id', iframeId);
iframe.setAttribute('style', 'position:absolute;left:-9999px');
document.body.append(iframe);
}
iframe.setAttribute('src', src);
iframe.addEventListener('load', () => {
iframe.contentWindow.focus();
iframe.contentWindow.print();
const infanticide = () => {
iframe.parentElement.removeChild(iframe);
window.removeEventListener('focus', infanticide);
}
window.addEventListener('focus', infanticide);
});
};
It is difficult, due to different browser behavior after print. Desktop Chrome handles the print dialogue internally, so doesn't shift focus after print, however, afterprint event works fine here (As of now, 81.0). On the other hand, Chrome on mobile device and most of the other browsers shifts focus after print and afterprint event doesn't work consistently here. Mouse movement event doesn't work on mobile devices.
So, Detect if it is Desktop Chrome,
If Yes, use afterprint event. If No, use focus based detection. You can also use mouse movement event(Works in desktop only) in combination of these, to cover more browsers and more scenarios.
well, just to remind everyone that the afterprint will not determine the print action button instead it will execute whenever the print window is closed or closing, both cancel button or esc key which closing the print window will consider afterprint while there is no actual print happening yet.
Implementing window.onbeforeprint and window.onafterprint
The window.close() call after the window.print() is not working in Chrome v 78.0.3904.70
To approach this I'm using Adam's answer with a simple modification:
function print() {
(function () {
let afterPrintCounter = !!window.chrome ? 0 : 1;
let beforePrintCounter = !!window.chrome ? 0 : 1;
var beforePrint = function () {
beforePrintCounter++;
if (beforePrintCounter === 2) {
console.log('Functionality to run before printing.');
}
};
var afterPrint = function () {
afterPrintCounter++;
if (afterPrintCounter === 2) {
console.log('Functionality to run after printing.');
//window.close();
}
};
if (window.matchMedia) {
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function (mql) {
if (mql.matches) {
beforePrint();
} else {
afterPrint();
}
});
}
window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;
}());
//window.print(); //To print the page when it is loaded
}
I'm calling it in here:
<body onload="print();">
This works for me.
Note that I use a counter for both functions, so that I can handle this event in different browsers (fires twice in Chrome, and one time in Mozilla).
For detecting the browser you can refer to this answer