Stefan R
Stefan R

Reputation: 71

$window.focus() doesn't work on existing tabs in iOS Safari

When I open a new window with var win = window.open("", "name") and then focus the window using win.focus() this works for the first time in iOS Safari.

But when the existing window is referenced again by name using window.open I can't focus again in iOS Safari. In Chrome this works fine.

Is there any way how I can focus on an already existing tab just knowing the name?

I created a fiddle for testing: https://jsfiddle.net/szqnu38f/

Upvotes: 2

Views: 2207

Answers (3)

Nikolay Frantsev
Nikolay Frantsev

Reputation: 1

You can check if active tab loses focus and reuse open window when possible:

const references = {};

const openReference = (href) => {
  references[href] = open(href, href);
  if (!references[href]) return;

  references[href].addEventListener('load', () => {
    references[href].addEventListener('beforeunload', () => {
      delete references[href];
    });
  });
};

const handleNoBlur = (callback) => {
  let blurTimeout;

  const handleBlur = () => {
    clearTimeout(blurTimeout);
    removeEventListener('blur', handleBlur);
  };

  blurTimeout = setTimeout(() => {
    removeEventListener('blur', handleBlur);

    callback();
  }, 100);

  addEventListener('blur', handleBlur);
};

const openOrFocus = (href) => {
  const reference = references[href];

  if (reference && reference.closed === false) {
    handleNoBlur(() => {
      reference.close();
      openReference(href);
    });

    reference.focus();
  } else {
    openReference(href);
  }
};

openOrFocus('https://stackoverflow.com/');

Upvotes: 0

stewori
stewori

Reputation: 576

Until the bug is fixed by Apple, you may use the following workaround:

// replace win.focus() by:
win.close();
win = win.open("", "name");

Upvotes: 0

Stefan R
Stefan R

Reputation: 71

This seems to be a bug within iOS Safari.

Generally, it is not possible to set the focus again on an existing named tab. This is also the case when a link with target set to a name is clicked again after the tab was opened --> see https://jsfiddle.net/g3bk1v5a/4/

<a href="http://www.google.com" target="test">Test</a>

Therefore, I opened a bug report at Apple.

Upvotes: 4

Related Questions