iOS Safari - Give focus to window
Asked Answered
E

1

6

I've got this jsFiddle, which has a simple div with a jQuery click handler:

<div class="testDiv" 
   data-target="http://www.stackoverflow.com" 
   data-open="false">
</div>

$(document).ready(function(){
    var newWindow;
    $('.testDiv').on('click', function(e){
        var target = $(this).data('target');
        var open = $(this).data('open');

        if (!open){
            $(this).data('open','true');
            newWindow = window.open(target);
        }
        else {
            if (newWindow.closed){
                newWindow = window.open(target);
            }
            newWindow.focus();
        }
    });
})

The click handler on the div is designed to open a new window if it's not already open; if it's open, it gives that window focus. This works fine in Chrome on Win 7 x64 but on iOS 8.3's Safari (on an iPhone 6), once the window is open, clicking the div doesn't switch focus to the opened window. You have to close the window and open it again for it to gain focus.

Any solutions to this iOS Safari focus issue?

Earflap answered 12/5, 2015 at 14:2 Comment(0)
R
1

This works for me, tested on iOS (Tablet), MacOS (M1), Chrome:

const link = 'http://...';
const target = 'NEW_WINDOW'

let win = window.open(link, target);

if (win && !win.closed) {
  win.close();
}

win = window.open(link, target);

if (win) {
  setTimeout(() => win.focus(), 100);
}
Reserved answered 12/9, 2022 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.