Detect page change or reload

0

How can I detect a page change or reload so that I can show a confirmation alert if I want to leave the current page or not.

var res = confirm('It\'s time to change. Do you agree with me?');
  if (res) {
    event.target.nextElementSibling.textContent = 'Yes, let\'s go for it.';
  } else {
    event.target.nextElementSibling.textContent = 'No, this is not the time.';
  }
    
asked by hubman 02.02.2018 в 17:54
source

2 answers

1

You can use the event onbeforeunload

window.onbeforeunload = function(e) {
    return "You have some unsaved changes";
};

From what I read, each browser can put different messages, it may not be possible to create a dynamic message.

According to answer browsers eliminated the possibility of leaving dynamic messages in different versions

    
answered by 02.02.2018 в 17:57
1

You can use the API of Performance , ( although there are or may be some compatibility problems) The same can be an option to detect the refresh , when this event happens, the type is 1 , from this you can perform the validation

  if (window.performance.navigation.type == 1) {
   if(confirm('Desea Actualizar ? ')){
     location.href ="https://w3c-test.org/navigation-timing/test_navigation_type_reload.html";
   }
else{
    alert('Correcto');
  }
}
    
answered by 02.02.2018 в 19:01