I'm running an app in a popup window. I have the following code in the head of my html file for one particular site:
<script type="text/javascript">
function navigate() {
window.location.href = "{{ next_page }}";
}
fetch("{{ next_page }}").then(navigate);
</script>
<script type="text/javascript">
window.addEventListener("unload", function() {
window.opener.location.replace("some-link");
})
</script>
The goal is to show the current page until another page loads (thus fetch.then(navigate)
) and -- at the same time -- be able to spot that the user closed the popup and redirect the user to another website whenever that happens.
The problem is, the parent window redirects to another website (some-link
) after 'next_page' loads.
Is there a way to prevent this behavior? Can I use the fetch.then
construction and still be able to spot the user closed the popup window?
CodePudding user response:
Set a globally available variable, set and access as appropriate. The following is a guide only and will need to be adjusted to suite your needs.
<script type="text/javascript">
window.detectUnload = true;
function navigate() {
window.detectUnload = false;
window.location.href = "{{ next_page }}";
}
fetch("{{ next_page }}").then(navigate);
</script>
<script type="text/javascript">
window.addEventListener("unload", function() {
if(window.detectUnload){window.opener.location.replace("some-link")}
});
</script>
Alternatively you could use removeEventListener
, but it could be tricky with the way your code is scoped in different script elements.