iframe表单提交后如何关闭窗口 [英] How to close window after iframe form submits
问题描述
我有一个空白页面,其中包含一个iframe,该页面显示了来自我的控制范围之外的外部域的表单.我正在尝试编写一些Javascript/jQuery,它将在提交表单后关闭窗口.
I have a blank page with an iframe that displays a form from an external domain outside my control. I'm trying to write a bit of Javascript/jQuery that will close the window after the form is submitted.
这是我的代码:
<body>
<script>
$('iframe input[type="submit"]').on('click', function () {
window.close();
});
</script>
<iframe src="SomeOtherDomain.com"></iframe>
</body>
但是,当我单击按钮时没有任何反应.我在做什么错了?
Nothing happens when I click the button though. What am I doing wrong?
我不确定是否会有所作为,但看起来iframe调用了第二个iframe ...我在iframe中有一个iframe.
I'm not sure if it makes a difference or not but it looks like the iframe calls a second iframe... I've got an iframe inside an iframe.
推荐答案
只要您的iframe src来自同一域,它就可以工作:
So long as your iframe src is from the same domain this will work:
$(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.
Simply remove the element but remember you can't get the contentDocument from an iframe that is not of the same domain.
工作解决方案: https://jsfiddle.net/f3eayurw/
这篇关于iframe表单提交后如何关闭窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!