我使用window.open()打开一个新窗口,将用户重定向到OAuth登录页面。然而,在成功登录后,当用户被重定向回我的应用程序时,在iOS上先前的带有window.open呼叫的窗口不会自动关闭。
在iPad上,它将关闭错误的窗口,而在iPhone上则根本无法关闭窗口。该代码在Android和桌面版Chrome和Firefox上运行良好。
经过多次尝试,我找到了一个解决方法(如下所示)。如果有更好的想法或根本原因,请在这里发表。
我使用window.open()打开一个新窗口,将用户重定向到OAuth登录页面。然而,在成功登录后,当用户被重定向回我的应用程序时,在iOS上先前的带有window.open呼叫的窗口不会自动关闭。
在iPad上,它将关闭错误的窗口,而在iPhone上则根本无法关闭窗口。该代码在Android和桌面版Chrome和Firefox上运行良好。
经过多次尝试,我找到了一个解决方法(如下所示)。如果有更好的想法或根本原因,请在这里发表。
在搜索了一番之后,我找到了这条推文,其中介绍了一个解决方法 - https://twitter.com/#!/gryzzly/statuses/177061204114685952 ,作者是 @gryzzly。
以下是完整的内容:
window.close() 在iOS上无法在 window.open() 或 target="_blank" 之后工作?请使用 setTimeout(window.close, timeout); 其中timeout > 300。
除此之外,我还删除了一个 .focus(),该函数在完全关闭新窗口之前将焦点放在父窗口上,这样就彻底解决了我的问题。
最终成功的代码如下:
在setTimeout中使用window.close函数无法生效,以下是测试结果:
我在以下环境中测试通过:
windows XP : Chrome20,Firefox12,IE8
Android gingerbread : android 浏览器
Android Ice Cream : android 浏览器, Firefox
Ipad : 默认浏览器(我猜是safari)
Iphone 3gs and 4s :默认
<SCRIPT LANGUAGE=\"JavaScript\">
function refresh() {
var sURL = unescape("http://(some web page)/");
window.location.replace(sURL);
}
function closeWindow() {
var isiPad = navigator.userAgent.match(/iPad/i) != null;
var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
if (isiPad || isiPhone) {
setTimeout( \"refresh()\", 300 );
} else {
window.close();
}
}
</SCRIPT>
...... and the html code .......
<p><input class="bigbutton" type="button" name="cancel" id="cancel" value="Cancel" onClick="closeWindow()"></p>
ios 12、13 可用
<p>If the page stops. Please press the button below to continue.</p>
<input id="button" name="button" type="submit" value="Close">
<script>
var ua = window.navigator.userAgent;
if (ua.indexOf('iPhone ') > 0) {
document.querySelector('#button').addEventListener('click', function (event) {
event.preventDefault();
window.close();
}, false);
document.querySelector('#button').click();
} else {
window.close();
}
</script>
window.addEventListener("load", window.close);
。 - Misha Reyzlin