JSFiddle - React, Tailwind, and code Playground

by micsel

HTML

<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>

CSS

.checkbox {
  margin-top: 20px;
  margin-left: 20px;
}

JavaScript

window.onload = () => {

  // declaration
  const defaultCounterValue = 10; // incremental --
  const defaultIntervalValue = 50; // ms
  let leavingSite = false;
  let counter = defaultCounterValue;

  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;
  };

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

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

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

  // Interval to check the state of user on the site
  setInterval(() => {
    if (leavingSite === true) {
      if (counter === 0) {
        checkbox.checked = false;
        setLocalStorage('checkbox', checkbox.checked);
        counter = defaultCounterValue;
        leavingSite = false;
      }
      counter--;
    }
  }, defaultIntervalValue);

  // Event that run before the user leaves
  window.onbeforeunload = (event) => {
    event.preventDefault = true;
    event.cancelBubble = true;
    event.returnValue = null;
    leavingSite = true;
  };
}