Standalone iOS webapp: Prevent opening Safari and keep current click-events

277 Views Asked by At

I have a mobile web app that's capable of running standalone. To prevent opening hrefs in Safari and keep them in the webapp, I did:

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;
                    }
        });
    }

However, this also keeps existing click-events from functioning that are bound to a-tags.

So I tried this but it does not work:

if (("standalone" in window.navigator) && window.navigator.standalone) {
        // For iOS Apps
        $('a').on('click', function(e){
                var ev = $._data(this, 'events');
                if(!ev && !ev.click) {
                    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;
                    }
                }
        });
    }

Any help is appreciated!

1

There are 1 best solutions below

0
On

I know this is an old question, so maybe you fixed it already, but I'll answer anyway in case it helps someone else. Moving the automatic-event-cancellation further down should do the trick.

So:

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) != '#' && $(this).attr('data-method') == undefined){
            window.location.href = new_location;
            return false; // Cancel the usual link-opening
        }
        // If the 'if' block above didn't run, process the click as normal
    });
}