Home  >  Article  >  Web Front-end  >  How to Handle onLoad Event for Windows Opened with window.open?

How to Handle onLoad Event for Windows Opened with window.open?

DDD
DDDOriginal
2024-10-24 14:40:02428browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn