I'm trying to open a tab multiple times using the JavaScript code given below..
function webAssign() {
let i;
let myWin;
for (i = 1; i < 4; i++) {
console.log(i);
myWin = window.open("index.html");
myWin.close();
}
}
After running this code, it throws the error given below..
Uncaught TypeError: myWin is null
How can I solve this problem?
From MDN's page for window.open:
Return value
A WindowProxy object, which is basically a thin wrapper for the Window object representing the newly created window, and has all its features available. If the window couldn't be opened, the returned value is instead
null.
(my emphasis)
There are contexts (environments where your code may be running) that can't open windows, or can't open windows to certain origins. In those contexts, window.open returns null. For example, the Stack Snippets feature here on SO disallows window.open:
function webAssign() {
let i;
let myWin;
for (i = 1; i < 4; i++) {
console.log(i);
myWin = window.open("index.html");
myWin.close();
}
}
webAssign();
Running that on Chrome gives the error (in the web console):
Blocked opening 'https://stacksnippets.net/index.html' in a new window because the request was made in a sandboxed frame whose 'allow-popups' permission is not set.
But separately from that, opening and immediately closing windows in a tight loop doesn't really make any sense.