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);
}
Related
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);
});
I want my javascript to be trigged when:
The current IE tab is switched out when multiple IE tabs are open.
When the current IE tab is closed.
I don't want my JS code be trigged by the in-page pops up dialogs.
When the whole IE window closed.
The lose focus event may not work for me because there are pop up diaglogs in my page, so when it pops out, the IE tab will lose focus, but since the tab is not switched or closed, I don't want my javascript to be trigged here.
Is there any solution? I am wondering if there's something like entering tab / leaving tab, or tab-switching events?
Some interesting links, but not resolve my question.
Is there a way to detect if a browser window is not currently active?
Hook into tab changed event of browser
if you use 'jQuery', you can easily do it .
$(window).blur(function(){
// your code
});
$(window).focus(function(){
// your code
});
here is the link which provides one more method to do it.
you may be interested in
(function(){
function doOnFocus(){ console.log("focus"); }
function doOnBlur(){ console.log("blur"); }
function doOnLeave(){ console.log("leave"); }
if('onfocusout' in document){
document.onfocusout = doOnBlur;
document.onfocusin = doOnFocus;
}else{
window.onblur = doOnBlur;
window.onfocus = doOnFocus;
}
window.onbeforeunload = doOnLeave;
})();
In javascript there is an event on window close it is not IE specific but is mostly used to call an alert before the user leaves the page. It's one of my pet peeves and is very annoying but may be what you are looking for.
window.onbeforeunload = yourfunctionthatexecutes;
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();
};
When I use the back button on Firefox to reach a previously visited page, scripts on that page won't run again.
Is there any fix/workaround to have the scripts execute again when viewing the page the second time?
Please note that I have tested the same pages on Google Chrome and Internet Explorer and they work as intended.
Here are the files and the steps I used to test the problem:
(navigate to 0.html, click to get to 1.html, back button)
0.html
<html><body>
<script>
window.onload = function() { alert('window.onload alert'); };
alert('inline alert');
</script>
Click Me!
</body></html>
1.html
<html><body>
<p>Go BACK!</p>
</body></html>
Set an empty function to be called on window.onunload:
window.onunload = function(){};
e.g.
<html><body>
<script type="text/javascript">
window.onload = function() { alert('window.onload alert'); };
window.onunload = function(){};
alert('inline alert');
</script>
Click Me!
</body></html>
Source:
http://www.firefoxanswer.com/firefox/672-firefoxanswer.html (Archived Version)
When I use the back button on Firefox to reach a previously visited page, scripts on that page won't run again.
That's correct and that's a good thing.
When you hit a link in Firefox (and Safari, and Opera), it does not immediately destroy your page to go onto the next one. It keeps the page intact, merely hiding it from view. Should you hit the back button, it will then bring the old page back into view, without having to load the document again; this is much faster, resulting in smoother back/forward page transitions for the user.
This feature is called the bfcache.
Any content you added to the page during the user's previous load and use of it will still be there. Any event handlers you attached to page elements will still be attached. Any timeouts/intervals you set will still be active. So there's rarely any reason you need to know that you have been hidden and re-shown. It would be wrong to call onload or inline script code again, because any binding and content generation you did in that function would be executing a second time over the same content, with potentially disastrous results. (eg. document.write in inline script would totally destroy the page.)
The reason writing to window.onunload has an effect is that the browsers that implement bfcache have decided that — for compatibility with pages that really do need to know when they're being discarded — any page that declares an interest in knowing when onunload occurs will cause the bfcache to be disabled. That page will be loaded fresh when you go back to it, instead of fetched from the bfcache.
So if you set window.onunload= function() {};, what you're actually doing is deliberately breaking the bfcache. This will result in your pages being slow to navigate, and should not be used except as a last resort.
If you do need to know when the user leaves or comes back to your page, without messing up the bfcache, you can trap the onpageshow and onpagehide events instead:
window.onload=window.onpageshow= function() {
alert('Hello!');
};
You can check the persisted property of the pageshow event. It is set to false on initial page load. When page is loaded from cache it is set to true.
window.onpageshow = function(event) {
if (event.persisted) {
alert("From bfcache");
}
};
For some reason jQuery does not have this property in the event. You can find it from original event though.
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
alert("From bfcache");
}
});
In my case window.onunload with an empty function didn't help (I tried to set a value for dropdown when user uses backwards button). And window.onload didn't work for other reason - it was overridden by <body onload="...">.
So I tried this using jQuery and it worked like a charm:
$(window).on('pageshow', function() { alert("I'm happy"); });
Wire in an "onunload" event that does nothing:
<html><body>
<script type="text/javascript">
window.onload = function() { alert('window.onload alert'); };
window.onunload = function(){};
alert('inline alert');
</script>
Click Me!
</body></html>
As far as i know Firefox does not fire onLoad event on back.
It should trigger onFocus instead based from this link here.
A simple way to cause a page to execute JavaScript when the user navigates back to it using browser history is the OnPopState event. We use this to pause and replay the video on our home page (https://fynydd.com).
window.onpopstate = function() {
// Do stuff here...
};
for some cases like ajax operations url change listener can be used
$(window).on('hashchange', function() {
....
});
I am trying to open new window from hyperlink using java script and then auto close it in five seconds. It either closes right away or doesn't close at all. Here are some samples of code I was using:
"function closeOnLoad(myLink){var newWindow=window.open(myLink);newWindow.onload=SetTimeout(newWindow.close(),5000);}" + LinkText + ""
You're better off closing the window from the parent instead of defining an onload handler within the child. Due to security restrictions, you simply may not have access to modify child window events.
function closeOnLoad(myLink)
{
var newWindow = window.open(myLink);
setTimeout(
function()
{
newWindow.close();
},
5000
);
};
}
you need to use what is called a 'closure' to wrap the timeout in. It's like the function to timeout and then close is wrapped within another function.
I won't go into detail here, but lookup javascript and closures and play around to see how they work.
Here's a link to help get you started: http://www.jibbering.com/faq/faq_notes/closures.html
The window closing code should be in the window's code:
$(document).ready(function() {
setTimeout(function() {
window.close();
},5000);
})
BUT, you will get a popup asking for the user to confirm if you try & close the popup that way.
To unload is the unload() function. Here you have an example.