【问题标题】:How to launch apps (facebook/twitter/etc) from mobile browser but fall back to hyperlink if the app isn't installed如何从移动浏览器启动应用程序(facebook/twitter/etc),但如果未安装应用程序,则退回到超链接
【发布时间】:2012-12-03 00:19:16
【问题描述】:

我希望可能有某种方法可以从浏览器中检测 uri:scheme 是否已在移动设备上注册。

IE:我想检查一下 facebook、twitter、pinterest 应用程序是否已安装并且可以从它们关联的 uri:scheme 启动。

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

如果用户安装了 facebook,则启动应用程序,但如果未安装应用程序,则回退到 fb 网站的移动版本。

【问题讨论】:

  • 也许您想检查是否安装了 FB 应用程序。检查这里,stackoverflow.com/questions/6382659/…
  • 我需要在浏览器中完成,与 Android 无关。
  • 这应该适用于所有移动平台吗?
  • @ŠimeVidas “这应该适用于所有移动平台吗?” - 它需要在浏览器中工作。
  • @taztodgmail...可能重复,是的...但至少这个有答案。

标签: javascript mobile-browser


【解决方案1】:

我想我有一个可行的解决方案。

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

【讨论】:

  • 我不知道对此的支持有多广泛,但它在 Firefox 中不起作用:fb://profile/10000 页面加载有效,但显示其“The地址不被理解”错误页面。
  • 我不知道原因,但这并不总是有效
  • 更好的方法是在您的应用程序中注册意图,因为它们现在可以侦听标准超链接。 IE:您可以将您的 iOS 和 Android 应用设置为监视对example.com/myspeciallink 的点击,当点击该链接时它会自动关闭您的应用。
猜你喜欢
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
  • 2015-01-24
  • 2014-06-24
  • 1970-01-01
相关资源
最近更新 更多