I’m encountering an issue with closing a child window inside a setTimeout callback in JavaScript. Despite successfully opening the child window using window.open, I am unable to access the newChild variable within the setTimeout callback function.
Here’s a simplified version of the code I’m working with:
import { useState } from "react";
const useButton = () => {
const openChildWindow = () => {
const newChild = window.open(
"https://www.google.com/",
"",
"toolbar=0,status=0,width=626,height=436"
);
setTimeout(() => {
newChild.close();
}, 3000);
};
return {
openChildWindow,
};
};
I’m perplexed as to why the newChild variable is not accessible within the setTimeout callback. Could someone please enlighten me on why this is happening and suggest a solution to fix this issue?
Thank you in advance for your assistance!
3
Answers
There can be couple of issues for this.
However the most common issue is that the new opened window is not of the same origin.
The window.open after successfully opening a new window returns a proxy object for new window. We can use this object to control the new window only if same-origin-policy (both the window are on same origin) is satisfied.
I tried and tested the code on stackoverflow page
Steps done:
I have tried to reproduce the issue above and came to know that, you have returned openChildWindow inside the useButton component. Basically there is no need to window component. because the window.open() will open a browser interface, i have updated the code below you can copy and try it in codeSandbox.
Your code works fine the way it is. The problem you are seeing, is that https://www.google.com/ is preventing the window from closing.
Try your code with other urls and see. The two I tested that worked fine are: