Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-10-24 14:40:02
Original
427 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!