Search code examples
javascriptwindowonblur

Close Child Window from Parent onblur using Javascript


I have code which returns some other page (Google) in a popup (child) window. I cannot write any code in child window and so I have to do everything from the parent. I am trying to bind the onblur event from parent to the child window so that the child window should be closed once it lost the focus. However, the child window splash for a micro second and closes automatically.

I can't use jQuery in the environment I am working.

Here is my sample code:

<html>
<head>
</head>

<body>
<input type="button" value="Open Google" onclick="OpenWindow()" />

<script type="text/javascript">

function OpenWindow()
{
    var url="http://www.google.com";

    var newWin=window.open(url, 'Popup','height=500,width=600,left=100,top=100,resizable=yes,scrollbars=no,toolbar=no,status=no');
    newWin.focus();
    newWin.onblur =  newWin.close();    
}
</script>

</body>
</html>

Solution

  • Just skip the parenthesis behind .close()

    newWin.onblur = newWin.close;
    

    You want to pass a function reference, you don't want to assign the value which gets returned by executing .close().