Opening a browser window from iOS Safari standalone mode

2 min.

This is a very specific edge case, so I’m gonna assume that if you are reading this, you came here from google having lost all hope and I do not need to explain the context of this issue.

So turns out Safari in iOS standalone mode has problems opening links in a new browser window if that link is located in an iframe. Window.open() will not work too. No other browser does that — not even Safari itself in a regular browser mode — so I suppose it’s just a bug.

After hitting my head on a wall for about a day I came up with this solution/hack. I’m not too happy about the fact that I had to write a hack to make the browser work as intended, but hey, you gotta do what you gotta do.

This snippet has to be included into the iframed website.

// a hack to handle safari standalone bug with
// opening links in new window on an iframe
if(('standalone' in window.navigator) && window.navigator.standalone) {
// listen for all clicks in the page
document.addEventListener('click', function(event) {
var elem = event.target;
// bubble up until we hit a link or top HTML element
while(elem.nodeName !== 'A' && elem.nodeName !== 'HTML') {
elem = elem.parentNode;
}
// check if we really have a link
if('href' in elem && elem.href.indexOf('http') !== -1 && elem.target.indexOf('blank') !== -1) {
event.preventDefault();

// create a dummy element to "click"
var link = window.parent.document.createElement('a');
link.target = '_blank';
link.href = elem.href;
link.click();
// the element is no longer needed
link = null;
}
}, false);
}

Do you have comments? Tweet X it at me.

Keep up with me

Consider subscribing. There's also an RSS feed if you're into that.

Wanna reach out? Tweet at me or drop me a line: golb [tod] sadat [ta] olleh.

Est. 2011