i know this question was asked before but i can't get this to work.
I have a .aspx which contains a function on the onunload body tag. This should refresh the parent page after the child page was closed.
At this point, i need to know if the page was refreshed/reloaded, because this logic will trigger the function call everytime and close my "child" page.
This is my code:
<script type="text/javascript">
function refreshparent(){
window.opener.location.reload(true);
window.close();
}
</script>
And this is what i want to do:
<script type="text/javascript">
function refreshparent(){
if(page.wasclosed){
window.opener.location.reload(true);
window.close();
}else{
//do nothing
}
}
</script>
this a part of is my aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body style="background-color: #d6eceb" onunload="refreshparent()">
A way to communicate between multiple tabs or windows (that have the some origin, e.g. https://yourdomain.com/) is with the Broadcast Channel API. With it, you can open communications between the tabs and send data back and forth.
This might be helpful in your case to have the child page tell the parent window that it is going to close. Use the beforeunload event to trigger sending a message before the child window is closed.
Apply the following scripts to their respective files.
This script opens a broadcast channel and listens for any incoming messages. Whenever the message is a string equal to 'refresh', then the page will reload.
<script type="text/javascript">
const channelName = 'form-closing-channel';
const channel = new BroadcastChannel(channelName);
channel.addEventListener('message', ({ data }) => {
if (data === 'refresh') {
window.location.reload();
}
});
</script>
This script only sends a message to other open parent window(s) just before it is going to close. The message that is sent will be 'refresh', which should trigger the reload in the parent.
<script type="text/javascript">
const channelName = 'form-closing-channel';
const channel = new BroadcastChannel(channelName);
window.addEventListener('beforeunload', () => {
channel.postMessage('refresh');
});
</script>
Important
Do note that all parent windows will respond to the received message. E.g. you have 3 open parent windows and 1 open child, closing the child will send 'refresh' to all of the parent windows and they will all reload.