'afterprint' event not firing on first page load in Chrome - javascript

I have a page where I need to hide some elements when the print dialog is opened via a button on the page. The basic functionality of the code is pasted below. Chrome is the required browser for this project and no other browsers are supported or allowed.
The issue is that the 'afterprint' event is not firing on the first load of the page. If I refresh the page, the code functions as expected. The steps to reproduce are:
Navigate to page in Chrome
Click print button
Click 'Cancel' in print dialog and 'afterprint' event does not fire.
The strange thing is that if I then refresh the page, the code works as expected. Another strange thing is that if I just double click the html file and it opens in chrome, then code works as expected. This is of course, assuming that chrome is set as the default application used to open html files. I can see the event getting registered in the Global Listeners in the Sources tab of the Chrome dev tools, but it does not fire.
<html>
<body>
<button id="print">Print</button>
<div id="prompt">
Hide if print dialog is open
</div>
<script>
document.getElementById('print').addEventListener("click", ev => {
document.getElementById('prompt').style.display = 'none';
window.print();
})
window.addEventListener('afterprint', ev => {
console.log('After print')
document.getElementById('prompt').style.display = 'block';
})
</script>
</body>
</html>
Any help is appreciated. Thank you.

I had this exact same issue... when the print button is clicked for the first time, the afterprint event listener did not fire.... But when I clicked the print button for the second time and any consecutive clicks fired the foresaid event listener... I solved this issue as follows
window.addEventListener('beforeprint', beforePrintFunction);
window.addEventListener('afterprint', afterPrintFunction);
window.print();
window.removeEventListener('beforeprint', beforePrintFunction);
window.removeEventListener('afterprint', afterPrintFunction);
This works well for me...

Related

How launch JavaScript function in every new opened tab or window of the same HTML page?

I have html page SomePage with onload event:
<body onload="someEvent()">
I attached to the SomePage js file with someEvent function:
function someEvent()
{
someFunction();
}
When I open SomePage, the someEvent function is launching in first tab. But it not launch when I open SomePage in new tab. How relaunch js function in every new opened tab or window of the same page?
Update:
When I run somePage in Visual Studio witn JavaScript debugging mode and put breakpoint in someEvent function, Debugger breaking it only in first opened tab, when I open second tab, Debugger do not break the point. Therefore, I decided, that my function not refreshed in second tab. After your answers I realized that it's not JavaScript problem and my previous example work correct only without breaking point in new opened tab. Thank you for your help.
It should work in every tab as long as long as you are loading the same page.
You can test by making an alert call in the onLoad callback function.
<body onload="someEvent()">
<script>
function someEvent()
{
alert('hi');
}
</script>
We may need more info on this. If you are just going to SomePage on a separate tab then anything that happened in the first tab should happen in the second. If that isn't what you are doing then the next tab is being opened by the first and that is where we need more info.
If I need to do something on load I usually set the following up in my javascript file and link it to my html page through a <script src="/path/to/file">
window.addEventListener("load", () => {
runFunctionAfterLoaf();
});
Try using
window.onload = function() {
someFunction();
};

Beforeunload event does not fire after page refresh Chrome

I have this simple code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<!--<script src="angular.min.js"></script>-->
<script>
window.onload = function () {
window.addEventListener("unload", function () {
debugger;
});
window.addEventListener("beforeunload", function () {
debugger;
});
window.onbeforeunload = function () {
}
}
</script>
</head>
<body ng-app="app">
</body>
</html>
I want unload or beforeunload events be fired after I refresh the page. This is not happening in Chrome Versión 67.0.3396.62. I have tried firefox and edge and it works well. It also works when i close the tab. The error ocurrs only when i refresh the page.
You've run into an issue that was already reported. It looks like a bug, but according to a Chrome dev (kozy) it is a feature:
Thanks for repro. It is actually feature. As soon as you pressed reload we ignore all breakpoints before page reloaded. It is useful all the time when you have a lot of breakpoints and need to reload page to restart debugging session.
Workaround: instead of pressing reload button you can navigate to the same url using omnibox then all breakpoint will work as expected.
I've added bold emphasis to point out the workaround proposed by kozy. I've tried it and found that it works.
Other than the issue with the debugger statement, the handlers are executed whether you are reloading or closing the tab. In both cases that follow, I get the stock prompt that Chrome provides when returning true:
window.addEventListener("beforeunload", function (ev) {
ev.returnValue = true; // `return true` won't work here.
});
This works too:
window.onbeforeunload = function () {
return true;
}
It used to be that you could use a return value with a message and the browser would show your custom message but browsers generally no longer support this.
Whether or not you want to set the handler for beforeunload inside a handler for load is entirely dependent on your goals. For instance, I have an application for editing documents that does not set the beforeunload handler until the application has started initializing, which is much later than the load event. The beforeunload handler is there to make sure the user does not leave the page with unsaved modifications.

jQuery $(window).on() does not work for popup window in IE11

I am trying to send data to a popup window which opens by clicking a button.
All my code is in php where I include javascript and html, I will just show html and js here.
Consider my popup window (say, popupwindow.html) code as just
<div id = 'getData'></div>
Now on the page(say, main.js) where I put the button clicking which the popup opens, I am computing some data and trying to send it to popupwindow.html.
Here is relevant main.js code that gets executed after clicking the button
var popup = window.open("popupwindow.html", "popup", extraParams); //ignore extraParams
$(popup).on('load', function() {
//console.log("inside onload function");
popup.document.getElementById("getData").innerHTML = data; //here data is some string
});
Now this code works perfectly on Chrome and Firefox, but in IE load() function does not get executed. I know this because the console.log line when uncommented, does not print on the console. Tried versions of jQuery from 1.2.3 to 2.2.1 where the code runs successfully on Chrome and Firefox(but not in IE)
Note: I cannot execute the required code on popup page(popupwindow.html) because of some constraints. I have to write it on main.js and send it to popup.
I saw all other questions which said onload() or similar function in IE gives problems but I still could not find the appropriate solution. Please let me know how I can fix this for IE.

Don't reload the popup in a chrome extension

I'm building a chrome extension and every time the user click on the icon the popup.html page is loaded(reloaded). Is there a way to load the popup page only the first time, or to load it in the background?
Here is the code from my background script
var x=false;
chrome.browserAction.onClicked.addListener(function(tab) {
if(x==false){
alert("test");
chrome.browserAction.setPopup({popup: "popup.html"});
}
});
So the alert("text") is triggered only one time, but the popup.html is changed every time I click the icon. In popup.html I simply generate a different random number.
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("test").innerHTML=Math.random();
});
Thanks
Everytime a users clicks the browserAction button chrome will open or close the attached popup. There is no way to stop it.

After travelling back in Firefox history, JavaScript won't run

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() {
....
});

Categories