window.focus() not working in Safari

I am trying to test a simple JS code snippet with window.focus()

Its working fine in Chrome, but not working in Safari

Can someone help me to figure out the issue


<!DOCTYPE html>
<head>
    <title>Test window.focus() in Safari</title>
</head>
<body>
    <button onclick="openWindow()">Test button</button>
</body>
<script>
    function openWindow(){
        var win = window.open();
        win.document.write("Howdy");
        win.focus();
    }
</script>
</html>

Posted on Aug 10, 2020 9:11 PM

Reply
Question marked as Top-ranking reply

Posted on Aug 11, 2020 4:36 AM

If you were hoping that you could force Safari to switch browser tabs with this code, it isn't going to happen due to browser security. What you can do is force Safari to open a new window (even when it is set to open new tabs by default, by using the following code:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
    function openWindow() {
        var win = window.open("","", "modal=yes");
        win.document.write("Howdy");
        win.focus();
    }
    </script>
</head>
<body>
    <button onclick="openWindow()">Test button</button>
</body>
</html>



I ran the above code with, and without an ad blocker running, and it still worked.

1 reply
Question marked as Top-ranking reply

Aug 11, 2020 4:36 AM in response to akhilputhiry

If you were hoping that you could force Safari to switch browser tabs with this code, it isn't going to happen due to browser security. What you can do is force Safari to open a new window (even when it is set to open new tabs by default, by using the following code:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
    function openWindow() {
        var win = window.open("","", "modal=yes");
        win.document.write("Howdy");
        win.focus();
    }
    </script>
</head>
<body>
    <button onclick="openWindow()">Test button</button>
</body>
</html>



I ran the above code with, and without an ad blocker running, and it still worked.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

window.focus() not working in Safari

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.