向浏览器中打开的另一个页面发送刷新请求


Send a refresh request to another page opened in the browser

我有一个页面A,它与页面b创建了一个窗口。

Page B向用户询问一些数据,将它们插入数据库,然后关闭自己。插入后,我试图使页面A自动刷新(它可以从A看到B已经关闭,或者由B本身在(或之后?)关闭之前触发的函数)

我该怎么做呢?

JavaScript的window.open()返回对打开窗口实例的引用。您可以使用它来设置onunload事件处理程序,像这样:

var hWndB = window.open('somepage.php'),
    hWndA = window.self;
hWndB.onunload = function(){ hWndA.location.reload(); }

可以使用onunload事件和window.opener事件。例如,

window.addEventListener('unload', function() {
   window.opener.location.reload();
}, false);

或者你可以使用jquery,这样你就不会有任何跨浏览器兼容性问题:

$(window).on('unload', function() {
   window.opener.location.reload();
});

还有一个叫做onbeforeunload的事件,你可能想看看。

编辑

对于旧的浏览器,您可以使用@CORRUPT在评论中提供的hack: window.open()在第二次调用

时返回undefined或null

变型"A seeing B closed":

//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);
}

变型"B踢A":

opener.rerfreshMySelf();
window.close() //Existing: B closes

两个变体都需要refreshMySelf()函数来刷新页面。如何做到这一点取决于页面机制,但是非ajax页面的起点是

function refreshMySelf() {
  location.reload();
}