Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect closing of window which opened with HTML form target="_blank" and different domain

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.

like image 530
kit Avatar asked Oct 28 '15 10:10

kit


1 Answers

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>
like image 115
kit Avatar answered Nov 13 '22 15:11

kit