【问题标题】:Detect closing of window which opened with HTML form target="_blank" and different domain检测以 HTML 表单 target="_blank" 和不同域打开的窗口的关闭
【发布时间】:2015-10-28 10:15:15
【问题描述】:

由于某些原因,我需要使用原生 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>

当用户点击Submit时,浏览器中会出现一个窗口/选项卡,我无法访问来自anotherDomain.com的表单响应。

如何检测_blank窗口何时关闭?

如果使用window.open(),我可以获得孩子的window 参考,但这不合适,因为window.open() 会被浏览器阻止。

【问题讨论】:

    标签: javascript html forms


    【解决方案1】:

    这是我的解决方案:

    <!-- 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>
    

    【讨论】:

      【解决方案2】:

      您必须在表单操作中使用 javascript:Window.open 方法,而不是使用目标属性。

      通过在 javascript 中打开新窗口,您将获得一个句柄 (myWin): var myWin = Window.open(,"_blank",

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-02
        • 2015-09-25
        • 2015-01-16
        • 1970-01-01
        • 2013-09-17
        • 1970-01-01
        • 2020-03-19
        • 2016-02-15
        相关资源
        最近更新 更多