Mobile Safari Page being hidden or unloaded for Deep Linking

Is there an event in mobile safari that can detect when a page is hidden due to a redirect? I want to open my app directly if it's installed, try Facebook if it's installed, and go to the webpage for that id if neither are available.

  1. If 'myapp' is installed, open myapp. The safari tab still redirects to facebook.com
  2. If 'myapp' is not installed, but Facebook is, open the Facebook iOS app. The safari tab still redirects to facebook.com

I've set up a test link with the following HTML/JS:

    <!DOCTYPE html>
    <html>
    <head>
            <title>Redirect Test</title>
            <script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
            <meta name='viewport' content='initial-scale = 1.0,maximum-scale = 1.0' />
    </head>
    <body>
    <button>Open Oreo</button>
    <script type='text/javascript'>
    jQuery(function(){
            jQuery( 'button' ).on( 'click', function(){
                    var myid = null, fbid = null;

                    // Watch for page leave to kill timers
                    jQuery( window ).on( 'pagehide pageshow blur unload', function(){
                            if ( myid ) {
                                    clearTimeout( myid );
                            }
                            if ( fbid ) {
                                    clearTimeout( fbid );
                            }
                    });

                    window.location = "myapp://fbprofile/oreo";
                    var myid = setTimeout(function(){

                            // My app doesn't exist on device, open Facebook
                            window.location = "fb://profile/oreo";
                            fbid = setTimeout(function(){

                                    // Facebook doesn't exist on device, open Facebook mobile
                                    window.location = "https://www.facebook.com/oreo";
                            }, 100);
                    }, 100);
            });
    });
    </script>
    </body>
    </html>

Answer №1

Great job on your code!
UPDATE: (note: removed suggestion regarding adding return false;)

Consider implementing a check within your setTimeout functions instead of just clearing them. Clearing timeouts can be more effective for intervals rather than one-time setTimeout calls. Also, it's advisable to verify that the user is not using a desktop browser before attempting native app protocols like app:// or fb://, as these browsers may try to follow those locations and display an error.

Here is a suggested script to try out:

<!DOCTYPE html>
<html>
<head>
    <title>Redirect Test</title>
    <script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
    <meta name='viewport' content='initial-scale = 1.0,maximum-scale = 1.0' />
</head>
<body>
<button>Open Oreo</button>
<script type='text/javascript'>
var mobileExp = /android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|ip(hone|od)|iris|kindle|lge |maemo|midc|mmp|mobile|o2|opera mini|palm( os)?|plucker|pocket|pre\/|psp|smartphone|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce; (iemobile|ppc)|xiino/i;

jQuery(function(){
    jQuery( 'button' ).on( 'click', function(){

        // Prevent desktop browsers from failing on a nativeapp:// protocol
        if(!mobileExp.test(navigator.userAgent)) {
            window.location = "https://www.facebook.com/oreo";
            return;
        }

        var clicked = +new Date, timeout = 100;

        window.location = "myapp://fbprofile/oreo";

        setTimeout(function(){
            // If we're still here after a (timeout), try native facebook app
            if (+new Date - clicked < timeout*2){
                console.log('clicked '+ (+new Date - clicked) +' ago- go to FB');
                window.location = "fb://profile/oreo";
            } else {
                console.log('too late for facebook');
            }
            setTimeout(function(){
                // If we're still here after another (timeout), try facebook web app
                if (+new Date - clicked < timeout*2){
                    console.log('clicked '+ (+new Date - clicked) +' ago- go to browser');
                    window.location = "https://www.facebook.com/oreo";
                } else {
                    console.log('too late for browser');
                }
            }, timeout);
        }, timeout);
    });
});
</script>
</body>
</html>

Feel free to uncomment the console logs and experiment with the value of timeout. This code has been successfully tested in IOS 6.1 Safari and Safari 6.0.2 Mac. Best of luck!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Selenium was unable to scroll a sidebar or container

I'm just starting out with selenium and python. I'm trying to scrape the content from a website that has a sidebar (container), and I need to copy its content multiple times while scrolling until I reach the end of the container. However, I&apos ...

Detecting collisions between images that have been rotated using CSS animations

My project involves using CSS animations and jQuery to create a simulation of cars moving at a crossroads from a top-down perspective for a driving license quiz. Users must select the order in which the cars will cross by clicking on them. Sample Image: ...

I am having trouble executing a script as the steps I have followed are not yielding the desired results. I am wondering where I may have made a mistake

I am trying to execute a script provided by Maciej Caputa in response to this question: How to import CSV or JSON to firebase cloud firestore The objective is to utilize a JSON file for uploading data to Cloud Firestore. As a newcomer to running scripts, ...

Struggling with jquery .append issue

Here is the HTML code snippet: <div class="expand"> <div class="title" id="SectionTitle2">Academics</div> <input type="button" onclick="showTitleForm('2');" name="editTitle2" value="Edit Title"> <form id="titleForm2" m ...

Seeking assistance with Shopify - Enhancing User Experience with Javascript Cookies

Is there a way to adjust the settings of how long Shopify stores cookies on your computer for? Currently, it retains cart information for two weeks. Any suggestions on how to modify this? I am considering two possibilities: 1) Making shopping members-only ...

Continuous Scrolling of Div in jQuery

I have successfully implemented a jQuery slider that allows me to click on the next arrow and slide to the next image. However, I am now facing the challenge of making it scroll continuously. This means that when I reach the last image in the slider, the f ...

Having difficulty defining properties within a JavaScript class

Currently, I am trying to set properties within a JavaScript class: class BookingReports extends ReportsInterface{ var categoryID; constructor() { super(); } init(CatID) { this.categoryID=CatID; } } H ...

The functionality of $(selector).css() seems to be malfunctioning

I currently have an html div element stored in a variable var rows = ""; rows += "<div>1111 : Hi there</div>"; Despite multiple attempts, I have failed to add a background color to this div using the following methods: 1. $(rows).css({&apos ...

Refreshing a Singular TableView Cell Label

I'm currently working on developing a cell in which there is a 'count' variable that serves as a label displaying the number of items located within a folder. To accomplish this, I am utilizing a fetch request within the `cellForRowAt` funct ...

Unable to receive any response with AJAX requests

Welcome to my HTML page <html> <head> <title>Using AJAX</title> </head> <script type="text/javascript" src="ajax.js"></script> <body> <form action="searchItems.php" name="searchItem" method="p ...

Retrieve characters preceding and following a space (JavaScript)

In my Angular component, I have a phone number field. For example, +36 42534534534 I am trying to extract the code before the space and the phone number after the space. This is how I am currently handling it: set phoneNumberResult(value: string) { ...

Should I use a tooltip or a pop-up for the tablet version?

I'm currently working on a web application that involves presenting 10 questions, each with 3 possible answers. For each answer, I require a tooltip or popover that provides guidance. While I have attempted to use tooltips and popovers, there is an is ...

"Utilizing jQuery to create a seamless loop with easing effects and the

I've been working on some code where I want elements to appear one by one with a delay of 700ms. Currently, all the elements are showing up at once. I've tried using setInterval and setTimeout functions but haven't had any success. If any ...

How to properly display an Angular Template expression in an Angular HTML Component Template without any issues?

When writing documentation within an Angular App, is there a way to prevent code from executing and instead display it as regular text? {{ date | date :'short'}} Many sources suggest using a span element to achieve this: <span class="pun"&g ...

Router integrated Vue modal

As a beginner in Vue, I am working on a simple app that showcases a list of countries. The main functionality is to display detailed information about a particular country in a modal when clicked. Unfortunately, I am facing an issue with the modal displayi ...

Need to invoke a controller method multiple times? Utilize AJAX for seamless and efficient execution

Apologies if this question seems simple, but I'm struggling to find a solution. I've implemented a straightforward method in a controller: public string ExactSeconds() { string str = DateTime.Now.Second.ToString(); return str; ...

Tips for efficiently arranging tableview cells

In my table view, I have two types of cells: one for original post comments and another for comments on those comments. Currently, the cells are displayed correctly but in no specific order. What I want is to arrange them in a particular order where commen ...

What is the best way to manage two map views within a single xib file?

Is it feasible to include two map views in a single XIB file? If so, how can different data be displayed on each map view? I have conducted extensive research but have been unable to find any relevant resources. if (myMapviewLala.tag==1) { MKCoordin ...

Sending requests across domains from HTTPS to HTTP with callback functionality, and reversing the process

Prior to our conversation, I had created it using Flash. I uploaded a special file (crossdomain.xml) on the server side (https), while the Flash component was placed on the http server. Although they belong to different domains on the https and http serv ...

Error: Attempting to access the 'set' property of an undefined object

As I work on developing a mern e-commerce site, I encountered an error on the sign-in page. Here are the steps I've taken to resolve it: 1. Updated 'Cookies->Cookie, set->Set' 2. Changed 'res.refresh_token' to res.refresh_ ...