ArticleZip > How To Run Function Of Parent Window When Child Window Closes

How To Run Function Of Parent Window When Child Window Closes

Have you ever wondered how to make a function run in the parent window when a child window closes? It's a common scenario in web development where you may need to perform certain tasks in the parent window based on actions taken in a pop-up or child window. In this guide, we'll walk you through a simple and efficient way to achieve this using JavaScript.

To start, you'll need a basic understanding of JavaScript and how windows interact with each other in a web browser. When you open a new window or pop-up using JavaScript, you can establish a reference to the child window to monitor its status and perform actions when it closes.

Here's a step-by-step guide to running a function in the parent window when the child window closes:

Step 1: Open the Child Window
First, you need to open the child window using the `window.open()` method in JavaScript. Make sure to store the reference to the child window in a variable for future use.

Javascript

// Open the child window
let childWindow = window.open('child.html', 'childWindow', 'width=400,height=300');

In this example, 'child.html' is the URL of the child window, 'childWindow' is the name of the window, and the dimensions specify the size of the child window.

Step 2: Monitor the Child Window
Next, you'll need to set up an interval to continuously check if the child window has closed. This is done by using the `setInterval()` method in JavaScript.

Javascript

let checkChild = setInterval(function() {
  if (childWindow.closed) {
    // Child window is closed, run the function in the parent window
    clearInterval(checkChild); // Stop checking
    myFunction();
  }
}, 1000); // Check every second

In this code snippet, we create an interval that checks every second if the child window is closed. Once the child window is closed, we clear the interval and call the `myFunction()` function in the parent window.

Step 3: Define the Function in the Parent Window
Finally, you need to define the function `myFunction()` in the parent window to be executed when the child window closes. This function can contain any actions or code that you want to run in response to the child window being closed.

Javascript

function myFunction() {
  // Perform actions in the parent window
  alert('Child window is closed!');
}

You can customize the `myFunction()` function to meet your specific requirements, such as updating data, reloading a page, or displaying a message to the user.

By following these three simple steps, you can easily run a function in the parent window when the child window closes. This technique allows you to create interactive and dynamic web applications that respond to user interactions seamlessly. Implement this solution in your projects to enhance the user experience and streamline your web development process.

×