beforeunload javascript code example

Example 1: javascript redirect

window.location.href = "http://mywebsite.com/home.html";

Example 2: js before unload

window.addEventListener('beforeunload', (event) => {
  // Cancel the event as stated by the standard.
  event.preventDefault();
  // Chrome requires returnValue to be set.
  event.returnValue = '';
});

Example 3: array.splice javascript

const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]

months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]

months.splice(0, 1);
// removes 1 element at index 0
console.log(months);
// expected output: Array ["Feb", "March", "April", "May"]

Example 4: javascript beforeunload

window.addEventListener("beforeunload", function(event) { ... });
window.onbeforeunload = function(event) { ... };

Example 5: brwoser prompt before reload

window.onbeforeunload = function(){ return 'Do you want to reload the page?';}

Tags:

Html Example