我希望可能有某种方法可以从浏览器中检测 uri:scheme 是否在移动设备上注册。
IE:我想检查 facebook、twitter、pinterest 应用程序是否已安装并且可以从其关联的 uri:scheme 启动。
if(fb_isInstalled) {
// href="fb://profile/...."
} else {
// href="http://m.facebook.com/..."
}
基本上,如果用户安装了 Facebook,则启动该应用程序,但如果未安装该应用程序,则回退到 Facebook 网站的移动版本。
最佳答案
我想我已经找到了可行的解决方案。
<!-- 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 提出来,你可以 fork 和搞乱。如果您愿意,还可以将 gist 包含在 jsfiddle 中。
<小时/>编辑
@kmallea fork 了要点并从根本上简化了它。 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();
});
关于javascript - 如何从移动浏览器启动应用程序(facebook/twitter/等),但如果未安装应用程序则退回到超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13675535/