Cha*_*ell 23 javascript mobile-browser
我希望可能有某种方法可以检测uri:scheme是否在浏览器中的移动设备上注册.
IE:我想检查是否安装了facebook,twitter,pinterest应用程序,并且可以从他们相关的uri:scheme启动.
if(fb_isInstalled) {
// href="fb://profile/...."
} else {
// href="http://m.facebook.com/..."
}
Run Code Online (Sandbox Code Playgroud)
基本上,如果用户已安装了facebook,则启动应用程序,但如果未安装该应用程序,则会回退到fb网站的移动版本.
Cha*_*ell 23
我想我有一个有效的解决方案.
<!-- links will work as expected where javascript is disabled-->
<a class="intent"
href="http://facebook.com/someProfile"
data-scheme="fb://profile/10000">facebook</a>
Run Code Online (Sandbox Code Playgroud)
我的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();
});
})();
Run Code Online (Sandbox Code Playgroud)
我也把它当作一个你可以分叉和捣乱的要点.如果您愿意,您还可以在jsfiddle中包含要点.
@kmallea分享了要点并从根本上简化了它. https://gist.github.com/kmallea/6784568
// tries to execute the uri:scheme
function uriSchemeWithHyperlinkFallback(uri, href) {
if(!window.open(uri)){
window.location = href;
}
}
Run Code Online (Sandbox Code Playgroud)
// `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();
});
Run Code Online (Sandbox Code Playgroud)