3

I have a form on my page. If it is changed because beforeunload event the user will have a dialog which catch the leave process.

If the user click on "continue" or "leave" then the new page is loading and form's data are lost.

If the user click on "cancel" the leave process is canceled.

How can we know when the user has clicked on cancel ?

Why I need to know that ?

In my case I have a switch button. When the user turns it on, the script tries to reload the page. If the user click on "continue" or "leave" it's ok. But if the user click on "cancel" I would like show back the switch on the position "off".

Pierre-Luc BLOT
  • 429
  • 7
  • 22

2 Answers2

1

When a user changes the button position ON and then attempts to leave but then cancel, the state of the button should change to OFF. We can use window.onbeforeunload function and returning false within the block of its code. Please see the below example, note that I have used checkbox instead of toggle switch, but you can type anything inside the window.onbeforeunload function to your desire.

 window.onbeforeunload = () => {
    document.getElementById("checkbox").checked = false;
    return false;
}
.checkbox {
  margin-top: 20px;
  margin-left: 20px;
}
<p>Clicking the link below should prompt with "Leave" or "Cancel" option. If you check the box, then click on the link, and then click on "Cancel", the checkbox should return to false.</p>

<div>
    <a href="https://www.google.com">Click here to exit this site and go to google.com</a>
</div>

<div class="checkbox">
    <input type="checkbox" id="checkbox">
</div>
Michael Seltene
  • 543
  • 1
  • 5
  • 17
  • When the checkbox is checked. I click on the link to leave the page. The dialog is opened. And then if I click on "cancel" the checkbox is correctly unchecked. But if I click on "leave" button of the dialog. The checkbox is unchecked too. It would be nice this checkbox stays checked. – Pierre-Luc BLOT Apr 26 '20 at 01:04
0

To handle the state of the button, we can use localStorage and setInterval timer to check if the user has left the site and onbeforeunload event to prompt user to leave or cancel. When user cancels, the interval counts down to 0, this means the user is still on your site and updates the localStorage, but if left, the interval will not continue and doesn't change the localStorage value, and therefore, when returning to your site, the checked button should be updated to the previous position. Note that, when you click Run code snippet on this site, it might not work for localStorage, run this code from your site or on JSFiddle. :-)

window.onload = () => {

  // declaration & Initialization
  const input = document.createElement("input");
  const defaultCounterValue = 10; // incremental --
  const defaultIntervalValue = 50; // ms
  const checkbox = document.getElementById('checkbox');
  const setLocalStorage = (itemName, itemValue) => {
    localStorage.setItem(itemName, itemValue);
  };
  const getLocalStorage = (itemName) => {
    return localStorage.getItem(itemName) === null ? false : localStorage.getItem(itemName) === 'false' ? false : true;
  };

  let interval = undefined;
  let counter = defaultCounterValue;

  setLocalStorage('checkbox', getLocalStorage('checkbox').toString());

  setTimeout(() => {
    checkbox.checked = getLocalStorage('checkbox');
  }, 0);

  checkbox.addEventListener('click', () => {
    setLocalStorage('checkbox', checkbox.checked);
  });

  // set input property and event handlers
  input.type = 'checkbox';
  input.checked = false;
  input.style.display = 'none';
  input.addEventListener('click', () => {
    let removeInterval = () => {
      clearInterval(interval);
      interval = undefined;
    }

    if (interval) {
      removeInterval();
    }

    interval = setInterval(() => {
      if (input.checked === true) {
        if (counter === 0) {
          checkbox.checked = false;
          setLocalStorage('checkbox', checkbox.checked);
          counter = defaultCounterValue;
          input.checked = false;
        }
        counter--;
      } else {
        removeInterval();
      }
    }, defaultIntervalValue);
  });
  document.body.appendChild(input);

  // Event that run before the user leaves
  window.onbeforeunload = (event) => {
    event.preventDefault = true;
    event.cancelBubble = true;
    event.returnValue = null;
    input.checked = false;
    input.click();
  };
}
.checkbox {
  margin-top: 20px;
  margin-left: 20px;
}
<p>Clicking the link below should prompt with "Leave" or "Cancel" option. If you check the box, then click on the link, and then click on "Cancel", the checkbox should return to false.</p>

<div>
  <a href="https://www.google.com">Click here to exit this site and go to google.com</a>
</div>

<div class="checkbox">
  <input type="checkbox" id="checkbox">
</div>
Michael Seltene
  • 543
  • 1
  • 5
  • 17