Using onafterprint in Chrome & Safari - javascript

I am aware that until recently onafterprint was only native to IE. Recently HTML5 has added it to its list of events. I have only been successful in using it in Firefox but cannot get it to function in Chrome or Safari.
It appears to only function in Firefox when its used in the body:
<body onafterprint="printIt()">
The script for the function is this:
$(document).ready(function() {
$('.printMe').click(function() {
window.print();
return false;
});
});
function printIt()
{
$('#confirmPrint').show();
};
By clicking the .printMe button, it opens the print window. Clicking print or cancel will show a message in #confirmPrint. I'm not so worried about being able to tell whether they are clicking cancel or print. I am only concerned with it functioning in Chrome and Safari. Any help is much appreciated. I am using jQuery as well, if that is not already obvious.

After some experiments, I think I can safely say that onafterprint is not worth considering.
Firefox fires it even if the user clicked Cancel instead of OK in the print dialog
IE8 apparently fires it even before the print dialog appears
Chrome doesn't fire it at all
Instead, just do whatever you wanted to do directly after calling print(), i.e.
$(document).ready(function() {
$('.printMe').click(function() {
window.print();
printIt();
return false;
});
});
function printIt()
{
$('#confirmPrint').show();
};

Related

Not able to show my own message on beforeunload event [duplicate]

When using window.onbeforeunload (or $(window).on("beforeunload")), is it possible to display a custom message in that popup?
Maybe a small trick that works on major browsers?
By looking at existing answers I have the feeling this was possible in the past using things like confirm or alert or event.returnValue, but now it seems they are not working anymore.
So, how to display a custom message in the beforeunload popup? Is that even/still possible?
tl;dr - You can't set custom message anymore in most modern browsers
A quick note (since this is an old answer) - these days all major browsers don't support custom message in the beforeunload popup. There is no new way to do this. In case you still do need to support old browsers - you can find the information below.
In order to set a confirmation message before the user is closing the window you can use
jQuery
$(window).bind("beforeunload",function(event) {
return "You have some unsaved changes";
});
Javascript
window.onbeforeunload = function() {
return "Leaving this page will reset the wizard";
};
      It's important to notice that you can't put confirm/alert inside beforeunload
A few more notes:
NOT all browsers support this (more info in the Browser compatibility section on MDN)
2. In Firefox you MUST do some real interaction with the page in order for this message to appear to the user.
3. Each browser can add his own text to your message.
Here are the results using the browsers I have access to:
Chrome:
Firefox:
Safari:
IE:
Just to make sure - you need to have jquery included
More information regarding the browsers support and the removal of the custom message:
Chrome removed support for custom message in ver 51
Opera removed support for custom message in ver 38
Firefox removed support for custom message in ver 44.0 (still looking for source for this information)
Safari removed support for custom message in ver 9.1
When using window.onbeforeunload (or $(window).on("beforeonload")), is it possible to display a custom message in that popup?
Not anymore. All major browsers have started ignoring the actual message and just showing their own.
By looking at existing answers I have the feeling this was possible in the past using things like confirm or alert or event.returnValue, but now it seems they are not working anymore.
Correct. A long time ago, you could use confirm or alert, more recently you could return a string from an onbeforeunload handler and that string would be displayed. Now, the content of the string is ignored and it's treated as a flag.
When using jQuery's on, you do indeed have to use returnValue on the original event:
$(window).on("beforeunload", function(e) {
// Your message won't get displayed by modern browsers; the browser's built-in
// one will be instead. But for older browsers, best to include an actual
// message instead of just "x" or similar.
return e.originalEvent.returnValue = "Your message here";
});
or the old-fasioned way:
window.onbeforeunload = function() {
return "Your message here"; // Probably won't be shown, see note above
};
That's all you can do.
As of 2021, for security reasons, it is no longer possible to display a custom message in the beforeunload popup, at least in the main browsers (Chrome, Firefox, Safari, Edge, Opera).
This is no longer possible since:
Chrome: version 51
Firefox: version 44
Safari: version 9
Edge: it has never been possible
Opera: version 38
For details see:
https://www.chromestatus.com/feature/5349061406228480
https://caniuse.com/mdn-api_windoweventhandlers_onbeforeunload_custom_text_support
An alternative approach in order to get a similar result is to catch click events related to links (that would take you away from the current page) and ask for confirmation there. It might be adjusted to include forms submission or perhaps redirections through scripts (that would require to apply a specific class and information in the elements that trigger the redirect).
Here is a working code snippet (based on jQuery) that shows you how you can do it:
Edit: the code snippet here in SO does not work on all browsers, for security reasons (the snippet generates an iframe... and in some browsers "Use of window.confirm is not allowed in different origin-domain iframes"), but the code DOES work, so give it a try!
$('body').on('click', function(e) {
var target, href;
//Identifying target object
target = $(e.target);
//If the target object is a link or is contained in a link we show the confirmation message
if (e.target.tagName === 'A' || target.parents('a').length > 0) {
//Default behavior is prevented (the link doesn't work)
e.preventDefault();
if (window.confirm("Are you really really sure you want to continue?")) {
//Identify link target
if (e.target.tagName === 'A') {
href = target.attr('href');
} else {
href = target.parents('a').first().attr('href');
}
//Redirect
window.location.href = href;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click me and I'll take you home
I just made a div appear that shows a message in the background.
It is behind the modal but this is better then nothing. It is kind of shady but at least you can give your user some info on why you bother her/him not to leave.
constructor($elem)
{
$(window).unbind().bind('beforeunload', (e) => this.beforeUnload(e));
}
beforeUnload(e)
{
$('#leaveWarning').show();
setTimeout(function(){
$('#leaveWarning').hide();
}, 1); // set this to 1ms .. since timers are stopped for this modal,
// the message will disappear right after the user clicked one of the options
return "This message is not relevant in most modern browsers.";
}
Here is a working Fiddle https://jsfiddle.net/sy3fda05/2/
You can't set a custom message on a modern browser instead you can use of default alert function.
checkout browser compatibility
Try this code for all all browsers supported
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Sure?';
}
// For Safari
return 'Sure?';
};
All the above doesn't work in chrome at least it need to add return false otherwise nothing happen.
window.onbeforeunload = function(e) {
$('#leaveWarning').show();
// the timer is only to let the message box disappear after the user
// decides to stay on this page
// set this to 1ms .. since timers are stopped for this modal
setTimeout(function() {
$('#leaveWarning').hide();
}, 1);
//
return false;
return "This message is not relevant in most modern browsers.";
}

window.onbeforeunload is not working in Firefox [duplicate]

When using window.onbeforeunload (or $(window).on("beforeunload")), is it possible to display a custom message in that popup?
Maybe a small trick that works on major browsers?
By looking at existing answers I have the feeling this was possible in the past using things like confirm or alert or event.returnValue, but now it seems they are not working anymore.
So, how to display a custom message in the beforeunload popup? Is that even/still possible?
tl;dr - You can't set custom message anymore in most modern browsers
A quick note (since this is an old answer) - these days all major browsers don't support custom message in the beforeunload popup. There is no new way to do this. In case you still do need to support old browsers - you can find the information below.
In order to set a confirmation message before the user is closing the window you can use
jQuery
$(window).bind("beforeunload",function(event) {
return "You have some unsaved changes";
});
Javascript
window.onbeforeunload = function() {
return "Leaving this page will reset the wizard";
};
      It's important to notice that you can't put confirm/alert inside beforeunload
A few more notes:
NOT all browsers support this (more info in the Browser compatibility section on MDN)
2. In Firefox you MUST do some real interaction with the page in order for this message to appear to the user.
3. Each browser can add his own text to your message.
Here are the results using the browsers I have access to:
Chrome:
Firefox:
Safari:
IE:
Just to make sure - you need to have jquery included
More information regarding the browsers support and the removal of the custom message:
Chrome removed support for custom message in ver 51
Opera removed support for custom message in ver 38
Firefox removed support for custom message in ver 44.0 (still looking for source for this information)
Safari removed support for custom message in ver 9.1
When using window.onbeforeunload (or $(window).on("beforeonload")), is it possible to display a custom message in that popup?
Not anymore. All major browsers have started ignoring the actual message and just showing their own.
By looking at existing answers I have the feeling this was possible in the past using things like confirm or alert or event.returnValue, but now it seems they are not working anymore.
Correct. A long time ago, you could use confirm or alert, more recently you could return a string from an onbeforeunload handler and that string would be displayed. Now, the content of the string is ignored and it's treated as a flag.
When using jQuery's on, you do indeed have to use returnValue on the original event:
$(window).on("beforeunload", function(e) {
// Your message won't get displayed by modern browsers; the browser's built-in
// one will be instead. But for older browsers, best to include an actual
// message instead of just "x" or similar.
return e.originalEvent.returnValue = "Your message here";
});
or the old-fasioned way:
window.onbeforeunload = function() {
return "Your message here"; // Probably won't be shown, see note above
};
That's all you can do.
As of 2021, for security reasons, it is no longer possible to display a custom message in the beforeunload popup, at least in the main browsers (Chrome, Firefox, Safari, Edge, Opera).
This is no longer possible since:
Chrome: version 51
Firefox: version 44
Safari: version 9
Edge: it has never been possible
Opera: version 38
For details see:
https://www.chromestatus.com/feature/5349061406228480
https://caniuse.com/mdn-api_windoweventhandlers_onbeforeunload_custom_text_support
An alternative approach in order to get a similar result is to catch click events related to links (that would take you away from the current page) and ask for confirmation there. It might be adjusted to include forms submission or perhaps redirections through scripts (that would require to apply a specific class and information in the elements that trigger the redirect).
Here is a working code snippet (based on jQuery) that shows you how you can do it:
Edit: the code snippet here in SO does not work on all browsers, for security reasons (the snippet generates an iframe... and in some browsers "Use of window.confirm is not allowed in different origin-domain iframes"), but the code DOES work, so give it a try!
$('body').on('click', function(e) {
var target, href;
//Identifying target object
target = $(e.target);
//If the target object is a link or is contained in a link we show the confirmation message
if (e.target.tagName === 'A' || target.parents('a').length > 0) {
//Default behavior is prevented (the link doesn't work)
e.preventDefault();
if (window.confirm("Are you really really sure you want to continue?")) {
//Identify link target
if (e.target.tagName === 'A') {
href = target.attr('href');
} else {
href = target.parents('a').first().attr('href');
}
//Redirect
window.location.href = href;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Click me and I'll take you home
I just made a div appear that shows a message in the background.
It is behind the modal but this is better then nothing. It is kind of shady but at least you can give your user some info on why you bother her/him not to leave.
constructor($elem)
{
$(window).unbind().bind('beforeunload', (e) => this.beforeUnload(e));
}
beforeUnload(e)
{
$('#leaveWarning').show();
setTimeout(function(){
$('#leaveWarning').hide();
}, 1); // set this to 1ms .. since timers are stopped for this modal,
// the message will disappear right after the user clicked one of the options
return "This message is not relevant in most modern browsers.";
}
Here is a working Fiddle https://jsfiddle.net/sy3fda05/2/
You can't set a custom message on a modern browser instead you can use of default alert function.
checkout browser compatibility
Try this code for all all browsers supported
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Sure?';
}
// For Safari
return 'Sure?';
};
All the above doesn't work in chrome at least it need to add return false otherwise nothing happen.
window.onbeforeunload = function(e) {
$('#leaveWarning').show();
// the timer is only to let the message box disappear after the user
// decides to stay on this page
// set this to 1ms .. since timers are stopped for this modal
setTimeout(function() {
$('#leaveWarning').hide();
}, 1);
//
return false;
return "This message is not relevant in most modern browsers.";
}

Safari print issue with javascript window.print()

I am having an issue with print on Safari. My System is Windows 7, and this function works fine in all other browsers except Safari. Here is the situation:
window.onload = function(){
console.log('before print');
window.print();
}
It won't output the log in console panel, but the print page will appear first, after i choose cancel in print page, the log will be output.
Does any body came up with this issue? Any help will be appreciated.
Updated
Here is the situation i have:
We need to print a page whose content can be changed by user by checking and unchecking check box, and only the content part of this page should be printed, so we create a new page that only contains the content for printing. In this page, we need to hide the unnecessary content that is not selected by user, so we need to do some DOM operation before window.print() get called. The console.log() is just an example code for observing. I tried to add an <div id='test'>Test HTML</div> in test HTML and add
var test = document.getElementById('test');
test.style.background = 'yellow';
before window.print();, it shows the same result in my Safari browser, the 'Test HTML' will not turn to yellow until i click cancel button in print panel, so it's not just the console.log issue.
Updated
I am using Safari 5.1.7(7534.57.2) on Windows 7
For me, the setTimeout solution didn't work. I found this jQuery plugin https://github.com/jasonday/printThis that has plenty of workarounds for window.print() because it seems not to be fully supported by all browsers.
I took this line that worked for me Safari document.execCommand("print", false, null)
and this worked ok for me for now in safari and chrome
try {
document.execCommand('print', false, null);
}
catch(e) {
window.print();
}
This is odd behavior. I tested in Safari 6.1 on Mac.
But may I ask why you need to log something before the printing? Because it seems that all the functions are being executed before the printing panel pops up:
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
window.onload = function() {
$('body').html('before print');
console.log('before print');
window.print();
};
</script>
When you look at the print preview, the page will have the text "before print" on it. For some reason, the console will log the text only when the print panel closes, but in my opinion that doesn't really matter for your visitors. You can manipulate DOM and change the page before the printing process as you like.
After several times trying, below code works, but i don't know the reason, can anybody explain? Or this is a Safari Bug?
window.onload = function() {
$('body').html('After change');
setTimeout(window.print, 1000);
};
Safari prints the page before it is loaded unlike other browsers. Hence window.onload() can be used in the code of the newly opened html page. But if the page opened is non html content, then it is not possible. The below solution is global across browsers and type of content open.
var printWindow = window.open(url, '_blank');
$(printWindow).load(function()
{
this.print();
});
Adding one more solution which worked for my case:
First make your popup window.
$( ".myButton" ).click(function() {
var url = 'www.google.com';
var printWindow = window.open( url, '_blank');
printWindow.focus();
});
Then, inside the HTML page which is loaded in the popup:
$(window).bind("load", function() {
setTimeout( function () {
try {
document.execCommand('print', false, null);
}
catch(e) {
window.print();
}
}, 500);
});

Window.onbeforeprint and Window.onafterprint get fired at the same time

I have defined onbeforeprint and I modify my html code and now once I finish printing that is on select of print button I want the onafterprint to be fired but it does not.
Instead when I press the Control + Print button the onbeforeprint is fired first and then the onafterprint event and then print dialog is shown.
Is there any way I could in some way do changes to my html after the Print button is clicked?
Am using IE -9 browser and the code is as follows:
Code
<script type="text/javascript">
window.onbeforeprint = function () {
alert('Hello');
}
window.onafterprint = function () {
alert('Bye');
}
</script>
onbeforeprint fired before dialog appears and allows one to change html and so on.
onafterprint is fired just before dialog appears. It is not even possible to know, whether document was actually printed or user canceled it. Needless to say about when printing finished (if started at all).
Again: no event is available to track anything happened in print dialog, i.e. answer to your question is no.
Moreover, I hope what your need will never be implemented, cause this allows to frustrate user. He/she asks to print one document, but got something different.
I ran into this same issue trying to use the onafterprint event, even in modern browsers.
Based on one of the other answers here, I was able to come up with this solution. It let's me close the window after the print dialog is closed:
// When the new window opens, immediately launch a print command,
// then queue up a window close action that will hang while the print dialog is still open.
// So far works in every browser tested(2020-09-22): IE/Chrome/Edge/Firefox
window.print();
setTimeout(function () {
window.close(); // Replace this line with your own 'afterprint' logic.
}, 2000);
Yes, you can, no catch. I have thus implemented in a professional application.
Print in Explorer, Firefox, all
window.onload = PrintMe;
function PrintMe() {
window.print();
setTimeout(function () {
alert("OK");
// Here you code, for example __doPostBack('ReturnPrint', '');
}, 2000);
}

Javascript popup - Works in FF & Chrome, fails in IE

I can't seem to figure out why the following simple popup will not work in IE9. FF & Chrome popup as expected, but IE does not appear to do anything when the link is clicked. I tried the IE9 debugger, but didn't get any helpful information out of it.
In the head section:
<script type="text/javascript" language="JavaScript">
function JSPopup(linkref) {
window.open(linkref,"Report Definitions","width=600,height=480");
return false;
}
In the body:
<strong>Report Definitions</strong>
Thanks for your help,
Filip
Turns out the problem was the name given to the popup - IE doesn't allow spaces, FF & Chrome do:
window.open(linkref,"Report Definitions","width=600,height=480");
needed to be changed to:
window.open(linkref,"ReportDefinitions","width=600,height=480");
This works across browsers.
Filip
This is part of the security changes made in IE6. Now you can only call "window.open" from within a user-initiated event. For example, your code would work inside an element's onclick event. The "window.open" http://msdn.microsoft.com/en-us/library/ms536651(VS.85).aspx MSDN page says this:
"This method must use a user-initiated action, such as clicking on a link or tabbing to a link and pressing enter, to open a pop-up window. The Pop-up Blocker feature in Internet Explorer 6 blocks windows that are opened without being initiated by the user."
Example...
function popUpWin(url,wtitle,wprop){
if (!window.open){ return; } // checking if we can't do this basic function
// Kill if(win), since win was a local var this was a usless check
var win = window.open(url,wtitle,wprop);
// next line important in case you open multiple with the same 'wtitle'
// to make sure the window is reused and refocused.
if (win && win.focus){ win.focus(); }
return false;
}

Categories