For some reasons, I need to use the native HTML form attribute target="_blank"
to display the form response in a new window.
I have the following HTML form in my myDomain.com
:
<form target="_blank" method="POST" action="http://www.anotherDomain.com/somePage">
<input name="someFieldName" value="someValue"/>
<button type="submit">Submit</button>
</form>
When the user clicked Submit
, a window/tab will appear in the browser, I have no access control to the form response from anotherDomain.com
.
How to detect when the _blank
window is closed?
I could get the child's window
reference if using window.open()
, but it is not suitable because window.open()
would be blocked by browser.
Here is my solution:
<!-- 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With