【发布时间】:2014-01-18 04:03:03
【问题描述】:
我需要知道链接是否会打开。
【问题讨论】:
标签: hyperlink
我需要知道链接是否会打开。
【问题讨论】:
标签: hyperlink
请参阅Maximilian Hoffmann's answer 以获得更强大的解决方案。
这样的方法很常见 - 劫持超时以重定向到不同的 URL。这种方法对你有用吗?
<a id="applink" href="comgooglemaps://?q=Red+Lobster+Billings">Show map</a>
<script type="text/javascript">
var backup = "http://maps.google.com/?q=Red+Lobster+Billings";
function applink(fail){
return function() {
var clickedAt = +new Date;
setTimeout(function(){
if (+new Date - clickedAt < 2000){
window.location = fail;
}
}, 500);
};
}
document.getElementById("applink").onclick = applink(backup);
</script>
【讨论】:
fail 网址。两者兼而有之。
解决方案是将带有 URL 方案的 iframe 添加到您的页面。如果未安装应用程序,它会静默失败,因此您需要通过计时器检查打开应用程序是否有效。
// detect iOS
if (['iPhone', 'iPad'].indexOf(navigator.platform) > -1) {
// create iframe with an Apple URL scheme
var iframe = document.createElement('iframe');
iframe.src = 'twitter://';
// hide iframe visually
iframe.width = 0;
iframe.height = 0;
iframe.frameBorder = 0;
// get timestamp before trying to open the app
var beforeSwitch = Date.now();
// schedule check if app was opened
setTimeout(function() {
// if this is called after less than 30ms
if (Date.now() - beforeSwitch < 30) {
// do something as a fallback
}
});
// add iframe to trigger opening the app
document.body.appendChild(iframe);
// directly remove it again
iframe.parentNode.removeChild(iframe);
}
我写了一个post with a more detailed example,它使用这种方法在 iOS 上打开 twitter 应用程序(如果已安装)。
【讨论】:
没有办法让您知道链接是否有效,但 Safari 有一个名为 Smart App Banners 的东西
<!DOCTYPE html>
<html>
<head>
<meta name="Google Maps" content="app-id=585027354"/>
</head>
<body>
The content of the document......
</body>
</html>
它的主要作用是检查是否安装了应用程序。如果未安装,用户将被定向到应用商店。如果已安装,用户将能够使用您通常使用 url 方案传递的相关数据从网站打开应用程序。 您可以将 if 用于 Google 地图。
这样做的缺点是它只能在 Safari 上运行,但总比没有好。
【讨论】: