我已经寻找了一段时间,但找不到符合我的需求的答案。我有一个页面弹出一个窗口(window.open),登录用户(创建cookie,设置session),然后重定向到另一个页面。在模态框重定向期间,我希望刷新父页面,以便父页面能够识别我刚刚完成的所有好事。我已经尝试过window.opener和类似的东西。有人能帮我一下吗?谢谢。
我已经寻找了一段时间,但找不到符合我的需求的答案。我有一个页面弹出一个窗口(window.open),登录用户(创建cookie,设置session),然后重定向到另一个页面。在模态框重定向期间,我希望刷新父页面,以便父页面能够识别我刚刚完成的所有好事。我已经尝试过window.opener和类似的东西。有人能帮我一下吗?谢谢。
window.opener
在弹出窗口中将引用打开窗口的window
对象,因此您当然可以调用 window.opener.location.reload();
。只要您不触犯同源策略,弹出窗口就可以像父级代码一样调用脚本和操纵父窗口对象的属性。
这里有一个实时示例演示子页面回调到父页面的函数,并直接操作父级。下面引用了这个例子的完整代码。
但是该示例并没有完全符合您的要求,因此我 也做了一个示例,其中子页面通过 window.opener.location.reload()
刷新父页面。
第一个实时示例的父级代码:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Parent Window</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<input type='button' id='btnOpen' value='Open Window'>
<div id='display'></div>
</body>
<script type='text/javascript'>
(function() {
var btnOpen = document.getElementById('btnOpen');
btnOpen.onclick = btnOpenClick;
function btnOpenClick() {
window.open('http://jsbin.com/ehupo4/2');
}
// Make the callback function available on our
// `window` object. I'm doing this explicitly
// here because I prefer to export any globals
// I'm going to create explicitly, but if you
// just declare a function in a script block
// and *not* inside another function, that will
// automatically become a property of `window`
window.callback = childCallback;
function childCallback() {
document.getElementById('display').innerHTML =
'Got callback from child window at ' + new Date();
}
})();
</script>
</html>
(您不必像我上面那样使用作用域函数,但将全局变量封装起来是有用的。)
第一个实例的子代码:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Child Window</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<p>I'm the child window</p>
</body>
<script type='text/javascript'>
if (window.opener) {
// Call the provided callback
window.opener.callback();
// Do something directly
var p = window.opener.document.createElement('p');
p.innerHTML = "I was added by the child directly.";
window.opener.document.body.appendChild(p);
}
</script>
</html>
window.parent.top.location = window.parent.top.location;(或类似的代码)
window.open()
应该返回对子窗口的引用...所以您可以执行child = window.open()
,然后您可以执行类似child.myParent = window
的操作。window.opener
是可靠的,除了 SOP 之外,这也会违反 SOP,但有多种选择总是好的。你必须处理一些时间问题,这也是我更喜欢让子页面调用父页面的原因之一。 - T.J. Crowder我在通过ajax提交模态框中的表单时遇到了相同的问题,需要重新加载底部页面(父页面)。window.location.reload();
对我有用。
window.parent.frames[0]
或类似的 https://developer.mozilla.org/en/DOM - David Yell