window.focus not working javascript; window.close works though?

Viewed 130

Objective: Warn User before leaving parent page if they have a Web Based Training Pop-up open. If they click cancel to stay on the page, I want the the focus back on the pop-up. Right now, it stays minimized and it's a problem.

This code works and the pop-up closes when I test:

window.open('', 'Popup').close();

If I test this, it does nothing:

window.open('', 'Popup').focus();

Full script:

window.onload = function () {
     window.addEventListener("beforeunload", function (e) {             

         if (window.open('', 'Popup') == null) {
             return undefined;
         }

          setTimeout(function () {
              setTimeout(function () {
                window.open('', 'Popup').focus();
            }, 1000);
        }, 1);

         var confirmationMessage = 'If you navigate away from this page, your open workshop will be closed';                   

         (e || window.event).returnValue = confirmationMessage; //Gecko + IE                
         return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
     });
1 Answers

Your code seems to be OK. But you can try below code and see if it works.

var url ='your URL'
var popWin = window.open(url, "Popup");
popWin.focus();
Related