Home >Web Front-end >JS Tutorial >How to Detect Window Onload Event in Popups

How to Detect Window Onload Event in Popups

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 12:55:31574browse

How to Detect Window Onload Event in Popups

Detecting Window Onload Event in Popups

Window.open is a primary method to open a new browser window or tab in JavaScript. By specifying parameters such as position, dimensions, and browser controls, you can customize the popup's appearance and functionality. However, there is no straightforward way to detect when the newly opened window has fully loaded.

In your sample code, you attempted to use $(window.popup).onload to handle the loading event, but it failed in all major browsers. To overcome this limitation, you need to employ a different approach.

The solution involves leveraging the native 'load' event listener. Here's how you can do it:

<code class="javascript">var myPopup = window.open(...);
myPopup.addEventListener('load', myFunction, false);</code>

This method attaches an event listener to the 'load' event of the myPopup window. When the page within the popup finishes loading, the myFunction function will be executed.

If you're targeting Internet Explorer, you'll need to use a slightly different approach as IE has conditional support for event listeners:

<code class="javascript">myPopup[myPopup.addEventListener ? 'addEventListener' : 'attachEvent'](
  (myPopup.attachEvent ? 'on' : '') + 'load', myFunction, false
);</code>

This conditional check allows the code to work in both IE and modern browsers. However, it's worth noting that supporting IE can be cumbersome and should be avoided if possible.

The above is the detailed content of How to Detect Window Onload Event in Popups. 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