Reputation: 325
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.
Upvotes: 11
Views: 2831
Reputation: 325
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>
Upvotes: 4
Reputation: 11
You have to use the javascript:Window.open method in you form action and not use target attribute.
By opening the new window in javascript you get an handle (myWin): var myWin = Window.open(,"_blank",
Upvotes: 0