Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Safari - Give focus to window

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?

like image 986
Alex Avatar asked Nov 21 '22 18:11

Alex


1 Answers

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);
}
like image 124
Felix Avatar answered Dec 18 '22 18:12

Felix