Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prevent internal links in iOS standalone web apps from opening in Mobile Safari
if (window.navigator.standalone) {
var local = document.domain;
$('a').click(function() {
var a = $(this).attr('href');
if ( a.match('http://' + local) || a.match('http://www.' + local) ){
event.preventDefault();
document.location.href = a;
}
});
}
@DanielApt

This comment has been minimized.

Copy link

@DanielApt DanielApt commented Feb 17, 2015

It would be better to delegate the events, then you will only attach one event handler, instead of multiple.

Change it to:

if (window.navigator.standalone) {
    var local = document.domain;
    $('document').on('click', 'a', function() {
        var a = $(this).attr('href');
        if ( a.match('http://' + local) || a.match('http://www.' + local) ){
            event.preventDefault();
            document.location.href = a;
        }
    });
}
@DanielApt

This comment has been minimized.

Copy link

@DanielApt DanielApt commented Feb 17, 2015

And also just flagging that this wouldn't work for urls starting with https://

@jtsay362

This comment has been minimized.

Copy link

@jtsay362 jtsay362 commented Mar 4, 2015

Some corrections

function escapeRegExp(string){
    return string.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
}

if (window.navigator.standalone) {
    var local = document.domain;
    $(document).on('click', 'a', function(event) {
        var a = $(this).attr('href');
        if ( a.match('https?://(www\\.)?' + escapeRegExp(local))){
            event.preventDefault();
            document.location.href = a;
        }
    });
}

Note document shouldn't be quoted and event should be added to the function signature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment