iPhone Safari Web App opens links in new window

IphoneSafariIphone Standalone-Web-App

Iphone Problem Overview


I have problem with web after adding icon to Home Screen. If the web is launched from Home Screen, all links will open in new window in Safari (and lose full screen functionality). How can I prevent it? I couldn't find any help, only the same unanswered question.

Iphone Solutions


Solution 1 - Iphone

I found JavaScript solution in iWebKit framework:

var a=document.getElementsByTagName("a");
for(var i=0;i<a.length;i++)
{
    a[i].onclick=function()
    {
        window.location=this.getAttribute("href");
        return false
    }
}

Solution 2 - Iphone

The other solutions here either don't account for external links (that you probably want to open externally in Safari) or don't account for relative links (without the domain in them).

The html5 mobile-boilerplate project links to this gist which has a good discussion on the topic: https://gist.github.com/1042026

Here's the final code they came up with:

<script>(function(a,b,c){if(c in b&&b[c]){var d,e=a.location,f=/^(a|html)$/i;a.addEventListener("click",function(a){d=a.target;while(!f.test(d.nodeName))d=d.parentNode;"href"in d&&(d.href.indexOf("http")||~d.href.indexOf(e.host))&&(a.preventDefault(),e.href=d.href)},!1)}})(document,window.navigator,"standalone")</script>

Solution 3 - Iphone

If you are using jQuery, you can do:

$("a").click(function (event) {
    event.preventDefault();
    window.location = $(this).attr("href");
});

Solution 4 - Iphone

This is working for me on iOS 6.1 and with Bootstrap JS links (i.e dropdown menus etc)

$(document).ready(function(){
    if (("standalone" in window.navigator) && window.navigator.standalone) {
      // For iOS Apps
      $('a').on('click', function(e){
        e.preventDefault();
        var new_location = $(this).attr('href');
        if (new_location != undefined && new_location.substr(0, 1) != '#' && $(this).attr('data-method') == undefined){
          window.location = new_location;
        }
      });
    }
  });

Solution 5 - Iphone

This is an old question and many of the solutions here are using javascript. Since then, iOS 11.3 has been released and you can now use the scope member. The scope member is a URL like "/" where all paths under that scope will not open a new page.

> The scope member is a string that represents the navigation scope of > this web application's application context.

Here is my example:

{
  "name": "Test",
  "short_name": "Test",
  "lang": "en-US",
  "start_url": "/",
  "scope": "/",
  ...
}

You can also read more about it here. I also recommend using the generator which will provide this functionality.

> If you specify the scope, everything works as expected similar to > Android, destinations out of the scope will open in Safari — with a > back button (the small one in the status bar) to your PWA.

Solution 6 - Iphone

Based on Davids answer and Richards comment, you should perform a domain check. Otherwise links to other websites will also opened in your web app.

$('a').live('click', function (event)
{      
    var href = $(this).attr("href");

    if (href.indexOf(location.hostname) > -1)
    {
        event.preventDefault();
        window.location = href;
    }
});

Solution 7 - Iphone

If using jQuery Mobile you will experience the new window when using the data-ajax='false' attribute. In fact, this will happen whenever ajaxEnabled is turned off, being by and external link, by a $.mobile.ajaxEnabled setting or by having a target='' attribute.

You may fix it using this:

$("a[data-ajax='false']").live("click", function(event){
  if (this.href) {
    event.preventDefault();
    location.href=this.href;
    return false;
  }
});

(Thanks to Richard Poole for the live() method - wasn't working with bind())

If you've turned ajaxEnabled off globally, you will need to drop the [data-ajax='false'].

This took me rather long to figure out as I was expecting it to be a jQuery Mobile specific problem where in fact it was the Ajax linking that actually prohibited the new window.

Solution 8 - Iphone

This code works for iOS 5 (it worked for me):

In the head tag:

<script type="text/javascript">
    function OpenLink(theLink){
        window.location.href = theLink.href;
    }
</script>

In the link that you want to be opened in the same window:

<a href="(your website here)" onclick="OpenLink(this); return false"> Link </a>

I got this code from this comment: iphone web app meta tags

Solution 9 - Iphone

Maybe you should allow to open links in new window when target is explicitly set to "_blank" as well :

$('a').live('click', function (event)
{      
    var href = $(this).attr("href");
    
    // prevent internal links (href.indexOf...) to open in safari if target
    // is not explicitly set_blank, doesn't break href="#" links
    if (href.indexOf(location.hostname) > -1 && href != "#" && $(this).attr("target") != "_blank")
    {
        event.preventDefault();
        window.location = href;
    }

});

Solution 10 - Iphone

I've found one that is very complete and efficient because it checks to be running only under standalone WebApp, works without jQuery and is also straightforward, just tested under iOS 8.2 :

Stay Standalone: Prevent links in standalone web apps opening Mobile Safari

Solution 11 - Iphone

You can also do linking almost normally:

<a href="#" onclick="window.location='URL_TO_GO';">TEXT OF THE LINK</a>

And you can remove the hash tag and href, everything it does it affects appearance..

Solution 12 - Iphone

This is what worked for me on iOS 6 (very slight adaptation of rmarscher's answer):

<script>                                                                
    (function(document,navigator,standalone) {                          
        if (standalone in navigator && navigator[standalone]) {         
            var curnode,location=document.location,stop=/^(a|html)$/i;  
            document.addEventListener("click", function(e) {            
                curnode=e.target;                                       
                while (!stop.test(curnode.nodeName)) {                  
                    curnode=curnode.parentNode;                         
                }                                                       
                if ("href" in curnode && (curnode.href.indexOf("http") || ~curnode.href.indexOf(location.host)) && curnode.target == false) {
                    e.preventDefault();                                 
                    location.href=curnode.href                          
                }                                                       
            },false);                                                   
        }                                                               
    })(document,window.navigator,"standalone")                          
</script>

Solution 13 - Iphone

This is slightly adapted version of Sean's which was preventing back button

// this function makes anchor tags work properly on an iphone

$(document).ready(function(){
if (("standalone" in window.navigator) && window.navigator.standalone) {
  // For iOS Apps
  $("a").on("click", function(e){

    var new_location = $(this).attr("href");
    if (new_location != undefined && new_location.substr(0, 1) != "#" && new_location!='' && $(this).attr("data-method") == undefined){
      e.preventDefault();
      window.location = new_location;
    }
  });
}

});

Solution 14 - Iphone

For those with Twitter Bootstrap and Rails 3

$('a').live('click', function (event) {
  if(!($(this).attr('data-method')=='delete')){
    var href = $(this).attr("href");
    event.preventDefault();
    window.location = href; 
  }   
});

Delete links are still working this way.

Solution 15 - Iphone

I prefer to open all links inside the standalone web app mode except ones that have target="_blank". Using jQuery, of course.

$(document).on('click', 'a', function(e) {
	if ($(this).attr('target') !== '_blank') {
		e.preventDefault();
		window.location = $(this).attr('href');
	}
});

Solution 16 - Iphone

One workaround i used for an iOS web app was that I made all links (which were buttons by CSS) form submit buttons. So I opened a form which posted to the destination link, then input type="submit" Not the best way, but it's what I figured out before I found this page.

Solution 17 - Iphone

I created a bower installable package out of @rmarscher's answer which can be found here:

http://github.com/stylr/iosweblinks

You can easily install the snippet with bower using bower install --save iosweblinks

Solution 18 - Iphone

For those using JQuery Mobile, the above solutions break popup dialog. This will keep links within webapp and allow for popups.

$(document).on('click','a', function (event) {
	if($(this).attr('href').indexOf('#') == 0) {
	    return true;
	}
    event.preventDefault();
	window.location = $(this).attr('href');		
});

Could also do it by:

$(document).on('click','a', function (event){
	if($(this).attr('data-rel') == 'popup'){
        return true;
	}
	event.preventDefault();
	window.location = $(this).attr('href');		
});
 

Solution 19 - Iphone

Here is what I'd use for all links on a page...

document.body.addEventListener(function(event) {
    if (event.target.href && event.target.target != "_blank") {
        event.preventDefault();
        window.location = this.href;                
    }
});

If you're using jQuery or Zepto...

$("body").on("click", "a", function(event) {
   event.target.target != "_blank" && (window.location = event.target.href);
});

Solution 20 - Iphone

You can simply remove this meta tag.

<meta name="apple-mobile-web-app-capable" content="yes">

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPavel LinkeschView Question on Stackoverflow
Solution 1 - IphonePavel LinkeschView Answer on Stackoverflow
Solution 2 - IphonermarscherView Answer on Stackoverflow
Solution 3 - IphoneDavid H.View Answer on Stackoverflow
Solution 4 - IphoneSeanView Answer on Stackoverflow
Solution 5 - IphoneAmir RaminfarView Answer on Stackoverflow
Solution 6 - IphoneThomas KekeisenView Answer on Stackoverflow
Solution 7 - IphoneJason PrawnView Answer on Stackoverflow
Solution 8 - Iphoneserin113View Answer on Stackoverflow
Solution 9 - IphonedaformatView Answer on Stackoverflow
Solution 10 - IphoneDavidTaubmannView Answer on Stackoverflow
Solution 11 - IphoneJonView Answer on Stackoverflow
Solution 12 - IphonebjhView Answer on Stackoverflow
Solution 13 - IphoneRichard TurnerView Answer on Stackoverflow
Solution 14 - IphonewoufView Answer on Stackoverflow
Solution 15 - IphoneAlex HaasView Answer on Stackoverflow
Solution 16 - Iphonedster77View Answer on Stackoverflow
Solution 17 - IphoneRobin van BaalenView Answer on Stackoverflow
Solution 18 - IphoneHexchaimenView Answer on Stackoverflow
Solution 19 - IphonealexView Answer on Stackoverflow
Solution 20 - IphoneSoohwan ParkView Answer on Stackoverflow