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!
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: