出于某些原因,我需要使用原生 HTML 表单属性 target="_blank"
来在新窗口中显示表单响应。
我的 myDomain.com
中有以下 HTML 表单:
<form target="_blank" method="POST" action="http://www.anotherDomain.com/somePage">
<input name="someFieldName" value="someValue"/>
<button type="submit">Submit</button>
</form>
当用户单击提交
时,浏览器中会出现一个窗口/选项卡,我无法控制来自anotherDomain.com
的表单响应。
如何检测_blank
窗口何时关闭?
如果使用 window.open()
,我可以获得 child 的 window
引用,但它不合适,因为 window.open()
会被浏览器拦截。
最佳答案
这是我的解决方案:
<!-- set form target to a specific name -->
<form target="windowName" method="POST" action="http://www.anotherDomain.com/somePage">
<input name="someFieldName" value="someValue"/>
<button type="submit">Submit</button>
</form>
<script>
var childWindow;
$('form').get(0).onsubmit = function () {
// I think why window.open() here would not be blocked by browser because the function is attached to the HTML DOM and the event is triggered by user (mouse click)
childWindow = window.open('', 'windowName');
};
var checkWindowClose = setInterval(function () {
if (childWindow.closed) {
alert('Window is closed');
clearInterval(checkWindowClose);
} else {
// check the URL if childWindow has been redirected to somewhere
try {
// cross-origin exception will occur if the URL is in different domain
if (childWindow.document.URL == 'something') {
// ...
clearInterval(checkWindowClose);
}
} catch (err) {
// just ignore the error and do nothing
}
}
}, 1000);
</script>
关于javascript - 检测以 HTML 表单目标 ="_blank"和不同域打开的窗口的关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33388294/