Javascript implementation prevents links in iOS APP from opening Safari browser

  • 2020-03-30 03:18:28
  • OfStack

Last time according to the online tutorial for their own website to get a Web APP, but the user's feeling is very bad.

Problem description:

What's the matter? It turns out that when you open a WEB APP and open a connection at random on the home page, you open Safari on your own terms. The original good camouflage and mood were all destroyed. What is to be done? The solution turned out to be quite simple. Just add the code. The experimental test passed on my iPhone (iOS 7.1) and iPod (iOS 6.1.4). According to the original author, the latest iOS 7.0.4 (iPhone and iPad) test passed, and the code should be compatible.

Problem solving:


<script type= " text/javascript " >  
//Clicking a link to jump to a new TAB in Safari in iOS Web APP
if (( " standalone "  in window.navigator) && window.navigator.standalone) {
    var noddy, remotes = false;
    document.addEventListener( ' click',
    function(event) {
        noddy = event.target;
        while (noddy.nodeName !==  " A "  && noddy.nodeName !==  " HTML " ) {
            noddy = noddy.parentNode;
        }
        if ( ' href' in noddy && noddy.href.indexOf( ' http') !== -1 && (noddy.href.indexOf(document.location.host) !== -1 || remotes)) {
            event.preventDefault();
            document.location.href = noddy.href;
        }
    },
    false);
}
</script>

It is recommended that you place the code in front of the /head tag and, of course, save it as a reference to a js file.


Related articles: