javascript 向浏览器中打开的另一个页面发送刷新请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16853138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send a refresh request to another page opened in the browser
提问by user1722791
I have page A that creates a window with the page B.
我有一个页面 A 用页面 B 创建一个窗口。
Page B asks the user some datas, inserts them in the database and then closes itself. After the insertion, I'm trying to make page A refresh automatically (it can be both from A seeing that B has closed, or by a function triggered by B itself before (or after?) closing)
页面 B 向用户询问一些数据,将它们插入到数据库中,然后自行关闭。插入后,我试图让页面 A 自动刷新(可以是从 A 看到 B 已经关闭,也可以是在关闭之前(或之后?)由 B 本身触发的功能)
How can I do that?
我怎样才能做到这一点?
回答by BlitZ
JavaScript's window.open()
returns reference to the instance of opened window. You may use it to set up onunload
event handler, like this:
JavaScriptwindow.open()
返回对打开窗口实例的引用。您可以使用它来设置onunload
事件处理程序,如下所示:
var hWndB = window.open('somepage.php'),
hWndA = window.self;
hWndB.onunload = function(){ hWndA.location.reload(); }
回答by lexmihaylov
You can use the onunload
event and window.opener
. For example.
您可以使用onunload
事件和window.opener
. 例如。
window.addEventListener('unload', function() {
window.opener.location.reload();
}, false);
Or you could use jquery so you wouldn't have any crossbrowser compatibility problems:
或者您可以使用 jquery,这样您就不会遇到任何跨浏览器兼容性问题:
$(window).on('unload', function() {
window.opener.location.reload();
});
Also there is another event called onbeforeunload
that you might want to take a look at.
还有一个叫做onbeforeunload
你可能想看看的事件。
EDIT
编辑
For older browser you can use the hack that @CORRUPT has provided in the comments: window.open() returns undefined or null on 2nd call
对于较旧的浏览器,您可以使用@CORRUPT 在评论中提供的 hack:window.open() 在第二次调用时返回 undefined 或 null
回答by Eugen Rieck
Variant "A seeing B closed":
变体“A 看到 B 关闭”:
//winb is global variable
winb=window.open(blah blah); //Existing: A opens B
window.setTimeout(checkWinB,1000);
function checkWinB() {
if (winb.closed()) refreshMySelf();
else window.setTimeout(checkWinB,1000);
}
Variant "B kicks A":
变体“B踢A”:
opener.rerfreshMySelf();
window.close() //Existing: B closes
Both variants need the refreshMySelf()
function to refresh the page. How to do this depends on the page mechanism, but a starting point for a non-AJAX page is
两种变体都需要refreshMySelf()
刷新页面的功能。如何做到这一点取决于页面机制,但非 AJAX 页面的起点是
function refreshMySelf() {
location.reload();
}