I have a page where the html elements reside and print function is called via javascript at the end.
<script type="text/javascript">
$(document).ready(function(){
window.print();
window.history.back();
})
</script>
now I have this code to redirect user after print or if cancel is clicked. it works on local but in live server it goes to the previous page immediately.
I have a page where the html elements reside and print function is called via javascript at the end.
<script type="text/javascript">
$(document).ready(function(){
window.print();
window.history.back();
})
</script>
now I have this code to redirect user after print or if cancel is clicked. it works on local but in live server it goes to the previous page immediately.
Share Improve this question edited Sep 2, 2016 at 4:39 Regolith asked Aug 29, 2016 at 8:12 RegolithRegolith 2,98210 gold badges35 silver badges53 bronze badges4 Answers
Reset to default 3Use this to go back to previous page
$(document).ready(function() {
window.print();
history.go(-1);
});
or:
$(document).ready(function() {
window.print();
history.back();
});
You could try with window.onafterprint
function.
The afterprint event is raised after the user prints or aborts a print dialog.
Unfortunately, only works in FF & IE
So for your code (and only for FF & IE), I will try with something like:
<script type="text/javascript">
$(document).ready(function(){
window.print();
})
window.onafterprint = function() {
history.go(-1);
};
</script>
Now, for Webkit-based browser use matchMedia('print')...
Something like...
var mediaQueryList = window.matchMedia('print');
mediaQueryList.addListener(function(mql) {
if (mql.matches) {
console.log('onbeforeprint equivalent');
} else {
console.log('onafterprint equivalent');
}
});
Source:
WindowEventHandlers.onafterprint
Detecting Print Requests with JavaScript
onbeforeprint and onafterprint is not working in Chrome and IE?
Maybe you should try print in a new window?
Something like this:
var myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>");
myWindow.document.close();
myWindow.focus();
myWindow.print();
myWindow.close();
myWindow.history.back();
Reference: JavaScript window.print() not working
(function() {
window.print();
setTimeout(() => {
history.back();
}, 500);
})();
This Will Work In All Browser This Will Get Back IN Previous Page When You Close Your Window window.print() This Will Execute Till Window Is Closed And After It Execute This Will Work Fine In All Browser