Is there a way to redirect my page to another page when hitting refresh using JavaScript

Viewed 249

enter image description hereSo im figuring out a way on how to redirect my page to another page when i hit the refresh button on my chrome but can't seem to find how to do it using JavaScript.

function confirmExit() {
  alert("exiting");
  window.location.href = "index.html";
  return true;
}
window.onbeforeunload = confirmExit();

When i use this code it just infinite loop.

2 Answers

A different solution is on page load, check for a localstorage field to see if it is the current URL. If so, redirect it to a different URL, if its different, set it to the current URL.

if(localStorage.getItem('current-url') === location.href){
    location.href = "redirectingurl";
}
else{
    localStorage.setItem('current-url',location.href);
}

I don't understand what you are trying to do but you cannot redirect by clicking the refresh button but one thing you can do open that other website in an iframe on your page

Related