espresso_coffee
espresso_coffee

Reputation: 6110

How to activate onbeforeunload after window.location reloads the page?

I use onbeforeunload in my project. However there is a section where user can click on the link and download report(s). Before window.location is being triggered I set window.onbeforeunload = null that way user won't be getting alert/confirm box with the question to leave or stay. There is a problem once they click on report and download the file if they try to close the browser onbeforeunload is not triggered again. How I can trigger onbeforeunload after report is downloaded? Here is example of my function:

function getReport(){
    var fileName = $(this).prop('id'),
    param = 'rptFile=' + fileName;  

    try{
        window.onbeforeunload = null;
        window.location = '/'+pathname+'/APPS/entry.cfm?idx=5&' + param;
    }catch(err){
        alert("An error occurred retrieving the file.");
    }
};

My main page that I'm reloading entry.cfm has document.ready function where I have onbeforeunload function. I expected once report is downloaded with window.location then onbeforeunload will br triggered again. So I'm not sure if I'm doing something wrong or this is not possible with JS. Here is entry.cfm example:

$(document).ready(function() {
    window.onbeforeunload = function () {
        return 'Are you sure you want to leave?';
    }
});

If anyone knows how to trigger onbeforeunload again please let me know. Thank you!

Upvotes: 0

Views: 1321

Answers (1)

Kresimir Pendic
Kresimir Pendic

Reputation: 3614

This will work, do not null window.onbeforeunload just replace your window.location with window.open to open report in new tab.

function getReport() {
  try {
    window.open('https://via.placeholder.com/350x150/ee5533', '_blank');
  } catch (err) {
    alert("An error occurred retrieving the file.");
  }
};


window.onbeforeunload = function() {
  return 'Are you sure you want to leave?';
}

$('.dwl').on('click', getReport );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a class="dwl">Try to download in new tab</a>

Upvotes: 1

Related Questions