Kri*_*ekk 8 javascript safari ios
在iOS'独立网络应用程序模式中,并且您单击链接时,该链接在Mobile Safari中打开,而不是保持独立模式.这对我来说毫无意义(至少对于内部链接而言).
我能想到修复此问题的唯一方法是向document节点添加一个单击处理程序,并手动导航如下:
if (window.navigator.standalone) {
document.addEventListener('click', (e) => {
if (e.target.tagName === 'A') {
e.preventDefault();
window.location = e.target.getAttribute('href');
});
}
Run Code Online (Sandbox Code Playgroud)
获得这种行为是否有一种不太常见的方式?这真的伤害了我的眼睛.
不幸的是,沿着这些思路做的事情是标准的做法。GitHub 上的 irae 整理了一个名为Stay Standalone 的脚本,它将为您处理所有脏活,并在各种边缘情况下进行了测试。虽然该脚本有点旧,但它确实可以在现代版本的 iOS 上运行。
它可能有点难看,但代码具有弹性,可以包含在通用 Javascript 包中。它不会改变其他场景的行为。这只是猜测,但我认为苹果选择这种行为的原因是独立的网络应用程序没有前进或后退按钮,单击链接可能会使应用程序处于“不可用”状态,并且对于不完全打算成为应用程序的网站。对于最终用户来说,这可能是一般情况下最理想的行为。
这是 Javascript 的副本:
(function(document,navigator,standalone) {
// prevents links from apps from oppening in mobile safari
// this javascript must be the first script in your <head>
if ((standalone in navigator) && navigator[standalone]) {
var curnode, location=document.location, stop=/^(a|html)$/i;
document.addEventListener('click', function(e) {
curnode=e.target;
while (!(stop).test(curnode.nodeName)) {
curnode=curnode.parentNode;
}
// Condidions to do this only on links to your own app
// if you want all links, use if('href' in curnode) instead.
if(
'href' in curnode && // is a link
(chref=curnode.href).replace(location.href,'').indexOf('#') && // is not an anchor
( !(/^[a-z\+\.\-]+:/i).test(chref) || // either does not have a proper scheme (relative links)
chref.indexOf(location.protocol+'//'+location.host)===0 ) // or is in the same protocol and domain
) {
e.preventDefault();
location.href = curnode.href;
}
},false);
}
})(document,window.navigator,'standalone');
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看测试。