本文汇总了JavaScript中刷新父页面的五种常见场景及对应代码。涵盖在iframe中刷新父页面、子窗口刷新父窗口、刷新以open()打开的窗口以及刷新showModalDialog()打开的对话框。通过parent、window.opener及execCommand等关键对象与方法的实际应用,帮助开发者快速解决页面数据同步问题。
iframe中刷新父页面
当页面包含iframe时,若需在子页面中刷新父页面,可使用parent对象定位父窗口并调用location.reload()方法。
<script language=JavaScript>
parent.location.reload();
</script>
普通弹窗刷新父页面
对于通过普通方式弹出的子页面,若需从子页面刷新父页面,应通过window.opener获取父窗口引用,随后执行location.reload()。
<script language=JavaScript>
window.opener.location.reload();
</script>
子窗口刷新父窗口
在子窗口中刷新父窗口的另一种写法是使用self.opener获取父窗口对象,并调用其location.reload()方法实现刷新。
<script language=JavaScript>
self.opener.location.reload();
</script>
刷新open()打开的窗口
针对通过window.open()方法打开的窗口,若需刷新父页面,可通过window.opener获取父窗口,并将其location.href重新赋值为当前href,以此触发刷新。
<script language=JavaScript>
window.opener.location.href=window.opener.location.href;
</script>
刷新showModalDialog()对话框
对于通过window.showModalDialog()方法打开的模式对话框,刷新父页面需调用window.parent.dialogArguments.document.execCommand('Refresh')命令。
<script language="javascript">
window.parent.dialogArguments.document.execCommand('Refresh');
</script>