Home >Web Front-end >JS Tutorial >How to Handle onLoad Event for Windows Opened with window.open?
Handling onLoad Event for Windows Opened with window.open
When using window.open to create a new window, the onload event listener may fail to work for the newly opened window. This article addresses this issue and provides a solution.
The following code demonstrates the issue:
<code class="js">window.popup = window.open($(this).attr('href'), 'Ad', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0'); $(window.popup).onload = function() { alert("Popup has loaded a page"); };</code>
This code will not work in major browsers like IE, Firefox, and Chrome. To resolve this issue, use the addEventListener method instead:
<code class="js">var myPopup = window.open(...); myPopup.addEventListener('load', myFunction, false);</code>
If you need to support IE, you can use the following fallback code:
<code class="js">myPopup[myPopup.addEventListener ? 'addEventListener' : 'attachEvent']( (myPopup.attachEvent ? 'on' : '') + 'load', myFunction, false );</code>
While supporting IE can be cumbersome, it is crucial to consider the target audience and make the necessary accommodations if needed.
The above is the detailed content of How to Handle onLoad Event for Windows Opened with window.open?. For more information, please follow other related articles on the PHP Chinese website!