Статьи

Глубокая мобильная связь для веб-сайтов и гибридных приложений

Автор Тим Севериен для Telerik Mobile Blog.

deep_linking_header

Время от времени появляется новая статистика, подтверждающая, что постоянно растущая доля онлайн-трафика исходит от мобильных устройств. Спецификация HTML5 отражает это, так как спецификация была наполнена API-интерфейсами, которые позволяют веб-приложениям использовать оборудование, обычно используемое в мобильных устройствах. Браузеры также реализуют ссылки, специфичные для операционной системы — например, когда вы просматриваете изображение, а не простой файловый браузер, вы можете выбирать между использованием приложения для фотографий устройства или камеры.

Еще одна особенность, ориентированная в первую очередь на мобильный трафик, — это глубокая связь , примитивная форма взаимодействия, позволяющая одному приложению открывать другое, в идеале в определенном виде или состоянии. Например, это позволит вам напрямую отобразить продукт в приложении для покупок или подготовить предварительно определенное сообщение в вашем любимом приложении обмена сообщениями, что может означать значительное улучшение общего пользовательского интерфейса вашего приложения!

Ина Тончева объясняет больше о глубоких связях в « Почему мобильным разработчикам следует заботиться о глубоких связях» .

Основное использование

Глубокие ссылки очень похожи на обычные ссылки на URL-адреса, но вместо ссылки на стандартный URL-адрес браузера мы ссылаемся на определенный URL-адрес, который зарезервирован и обрабатывается приложением.

У нас было это на рабочем столе целую вечность. Например, игровая платформа Steam зарезервировала собственный протокол (steam: //) для открытия вещей в клиенте Steam вместо веб-браузера. Тем не менее, эта статья посвящена использованию мобильного Интернета.

Ссылка, которая открывает WhatsApp, будет выглядеть так:

<a href="whatsapp://app">Open WhatsApp</a>
<a href="whatsapp://send?text=Hello%20World">Send "Hello World" via WhatsApp</a>

Поскольку эти ссылки относятся к конкретному приложению, вам придется искать их для конкретного приложения, которое вас может заинтересовать. GotSchemes — один из наиболее полных и точных ресурсов, которые я мог найти, чтобы найти эту информацию.

Это все, что есть. Спасибо за чтение этой статьи!

…Все еще здесь? Хорошо, потому что мы еще не закончили.

Проблемы — и как их преодолеть

Как бы просто это ни казалось, есть несколько вещей, которые мы должны рассмотреть.

  • Приложение установлено на клиенте?
  • Правильно ли выполнено устройство Deep Link?
  • Можно ли точно обнаружить все вышеперечисленное?

Ответ на эти вопросы: нет, мы не можем; не совсем точно. Не существует такого понятия, как «Определить API-интерфейс клиентского программного обеспечения», и я могу добавить, что на это есть веские основания. Я бы не хотел, чтобы вредоносный сайт смотрел на какие приложения я запускаю. К сожалению, это мешает нам создать стабильную ссылку.

Unlike the web, apps do not magically run on all platforms. A widely deployed app only works on a handful of operation systems. We can detect whether a client supports the apps by simply checking what OS the client is running, usually called “OS sniffing.” With that information, we can already determine if the client supports apps or not. Today, Android and iOS own roughly 92% of the market, so let’s focus on just these two for now.

Here’s an example of how to hide a link if the OS is not supported:

// If user agent does not meet criteria...
if(!navigator.userAgent.match(/iPhone|iPad|iPod|Android/i)) {
    // Get elements
    var links = document.querySelectorAll('a.mobile-deep-link');

    // Hide all the elements!
    Array.prototype.forEach.call(links, function(el) {
        el.style.display = 'none';
    });
}

Detecting if a link actually works is difficult. There are no events for this. When a link works, the user leaves the pages; something we can detect. If the user has not within a period of time, we redirect the browser to that app in the Play or App store. Sounds simple, right?

Using the Page Visibility API, we can detect whether a user is viewing the page. This API is in an early stages of development and has limited browser support. Luckily, Addy Osmani created Visibly.js, a sort of polyfill for the Page Visibility API, that uses focus and blur events as fallback.

By storing the fallback URLs in the DOM element, they can easily be referred to individually.

<a href="whatsapp://whatsapp?text=Hello%20World"
   data-store-android="https://play.google.com/store/apps/details?id=com.whatsapp"
   data-store-ios="https://itunes.apple.com/app/id310633997">
Say “Hello World” on WhatsApp!
</a>

First we detect the the Operation System by sniffing the User Agent string and detect if the OS supports mobile deep links. If so, all elements get a click handler in which we test whether a link has worked or not. If not, it opens the given URL of one of the attributes for that OS.

var links,
    os = {
        android: navigator.userAgent.match(/Android/i),
        ios:     navigator.userAgent.match(/iPhone|iPad|iPod/i)
    };

if(os.android || os.ios) {
    links = document.querySelectorAll('[data-store-android], [data-store-ios]');

    // Iterate through elements
    Array.prototype.forEach.call(links, function(el) {
        // Do something when link is clicked
        el.onclick = function() {
            var button = el,
                delay = 1000,
                start = new Date().getTime();

            // Start the timeout
            setTimeout(function() {
                var end = new Date().getTime();

                // Check if the page is visible
                // If this timeout is triggered after 2 * delay,
                // it's likely the user went away, the browser
                // didn't fire a blur event or alike and paused JS from executing
                // which means the link probably worked
                if(
                    visibly.hidden() ||
                    now - start >= delay * 2
                ) return;

                // Get shop URL
                var shop = os.android ? button.dataset.storeAndroid : button.dataset.storeIos;
                window.location.href = shop;
            }, delay);
        };
    });
}

Unfortunately, some browsers on Android appear to open the app without triggering a blur-like event nor pausing the code, resulting in the Play Store opening regardless, which can be somewhat annoying to your user.

All of this packed in a tool called deep-link.js, which is dedicated to providing an easy way to add deep links and to continuing the search for stable support.

Is the web ready for mobile deep links?

Using regular HTTP-links that can be opened by an app is the best choice by far, as seen on apps like Youtube and Ebay. However, provided the fixes above, support for custom schemes is pretty stable, though not perfect. Using deep links and the “hacks” described above should be a conscious consideration.

Ideally, all apps should handle regular URLs and serve the same content in the same manner for all platforms – but that’s never happening. Instead, vendors need to help by making cross-platform, mobile deep linking easier. Until then, we’ll have to be content running on some variation of this hack. But don’t many great things on the web platform seem to start with hacks?

Header image courtesy of gfpeck.