web-dev-qa-db-ja.com

モバイルブラウザーからアプリ(facebook / Twitter / etc)を起動する方法(アプリがインストールされていない場合はハイパーリンクにフォールバックする方法)

ブラウザ内からモバイルデバイスにuri:schemeが登録されているかどうかを検出する方法がいくつかあるといいのですが。

IE:Facebook、Twitter、Pinterestアプリがインストールされていて、関連するuri:schemeから起動できるかどうかを確認したいと思います。

if(fb_isInstalled) {
    // href="fb://profile/...."
} else {
    // href="http://m.facebook.com/..."
}

基本的に、ユーザーがFacebookをインストールした場合はアプリを起動しますが、アプリがインストールされていない場合は、fb Webサイトのモバイルバージョンにフォールバックします。

22
Chase Florell

私は実用的な解決策を持っていると思います。

 <!-- links will work as expected where javascript is disabled-->
 <a class="intent"   
    href="http://facebook.com/someProfile"   
    data-scheme="fb://profile/10000">facebook</a>

そして、私のJavaScriptはこのように動作します。
注:そこにはjQueryが少し混じっていますが、使いたくない場合は使用する必要はありません。

(function () {

    // tries to execute the uri:scheme
    function goToUri(uri, href) {
        var start, end, elapsed;

        // start a timer
        start = new Date().getTime();

        // attempt to redirect to the uri:scheme
        // the lovely thing about javascript is that it's single threadded.
        // if this WORKS, it'll stutter for a split second, causing the timer to be off
        document.location = uri;

        // end timer
        end = new Date().getTime();

        elapsed = (end - start);

        // if there's no elapsed time, then the scheme didn't fire, and we head to the url.
        if (elapsed < 1) {
            document.location = href;
        }
    }

    $('a.intent').on('click', function (event) {
        goToUri($(this).data('scheme'), $(this).attr('href'));
        event.preventDefault();
    });
})();

私はこれを Gist として投げましたが、フォークして混乱させることができます。必要に応じて、jsfiddleに Gist を含めることもできます。


編集する

@ kmallea 要旨を分岐し、大幅に簡略化しました。 https://Gist.github.com/kmallea/6784568

// tries to execute the uri:scheme
function uriSchemeWithHyperlinkFallback(uri, href) {
    if(!window.open(uri)){
        window.location = href;
    }
}
// `intent` is the class we're using to wire this up. Use whatever you like.
$('a.intent').on('click', function (event) {
    uriSchemeWithHyperlinkFallback($(this).data('scheme'), $(this).attr('href'));
    // we don't want the default browser behavior kicking in and screwing everything up.
    event.preventDefault();
});
22
Chase Florell