【问题标题】:How to close window after iframe form submitsiframe表单提交后如何关闭窗口
【发布时间】:2017-04-20 18:21:21
【问题描述】:

我有一个带有 iframe 的空白页面,该页面显示来自我无法控制的外部域的表单。我正在尝试编写一些 Javascript/jQuery 来在提交表单后关闭窗口。

这是我的代码:

<body>
    <script>
        $('iframe input[type="submit"]').on('click', function () {
            window.close();
        });
    </script>

    <iframe src="SomeOtherDomain.com"></iframe>
</body>

当我点击按钮时什么都没有发生。我做错了什么?

编辑:

我不确定它是否有区别,但看起来 iframe 调用了第二个 iframe...我在 iframe 中有一个 iframe。

【问题讨论】:

  • window 中的form 是使用window.open() 打开的吗?
  • @guest271314 - 不,我从未调用过 window.open()。
  • 如果您无法控制设置在.src&lt;iframe&gt; 的域,不确定是否可以将事件侦听器附加到iframe 的用户操作。 javascript at Question is at parent window of &lt;iframe&gt; 元素,对吗?
  • @guest271314 - 正确。

标签: javascript jquery iframe


【解决方案1】:

我相信您需要提供一些时间(100 毫秒)来提交表单数据。请通过调用 deleteIframeTimer 尝试此操作

     function deleteIframeTimer(){
      var t = setTimeout("deleteIframe()", 100);
     }

    function deleteIframe() {
         var iframe = parent.document.getElementById("myframe");
         iframe.parentNode.removeChild(iframe);
    }

【讨论】:

    【解决方案2】:

    只要您的 iframe src 来自同一个域,这将起作用:

    $(document).ready(function () {
    var f = $('#myframe')[0];
    var win = f.contentWindow;
    
    //Created test environment in IFrame with ID "myframe"
    $(win.document.body).append('<form><input type="submit" value="click me"/></form>');
    $(win.document).on('submit', function () {
        setTimeout(function () { $(f).remove();  }, 1000)
    });
    
    });
    

    只需删除元素,但请记住,您无法从不同域的 iframe 中获取 contentDocument。

    工作解决方案: https://jsfiddle.net/f3eayurw/

    【讨论】:

    • 很遗憾,iframe 源是另一个我无法控制的域。
    • 我相信你的要求是不可能的。 Cross Origin 将发挥作用。
    猜你喜欢
    • 2018-03-05
    • 2012-08-14
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    相关资源
    最近更新 更多