When i pile the following code , it works fine , but in console i get error: Uncaught TypeError: Cannot read property 'close' of undefined
<!DOCTYPE html>
<html>
<body>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
var myWindow;
function openWin(){
myWindow = window.open("", "myWindow");
}
function closeWin() {
myWindow.close();
}
</script>
</body>
</html>
When i pile the following code , it works fine , but in console i get error: Uncaught TypeError: Cannot read property 'close' of undefined
<!DOCTYPE html>
<html>
<body>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
var myWindow;
function openWin(){
myWindow = window.open("http://www.w3schools.", "myWindow");
}
function closeWin() {
myWindow.close();
}
</script>
</body>
</html>
var myWindow;
function openWin(){
myWindow = window.open("http://www.w3schools./", "myWindow");
}
function closeWin() {
myWindow.close();
}
i tried to call the above js file externally also, i get the same error
Share Improve this question edited Sep 3, 2015 at 9:28 mahesh asked Sep 3, 2015 at 9:27 maheshmahesh 391 gold badge1 silver badge11 bronze badges1 Answer
Reset to default 5You have to click Open "myWindow"
button before clicking the other one, because that is when the variable myWindow gets initial value.
You should check if window has been opened before trying to close it:
function closeWin() {
if(myWindow){
myWindow.close();
}
}
If myWindow
is not set, you just do nothing (as there is nothing to be closed, right?).