Running custom logic when user close the browser tab in JavaScript

In the last blog post, we learned how to interrupt users if they have unsaved data while closing the browser. You can read it here.

But we often need to just save the drafts and close the window without using getting the prompt. It requires a slight tweak in the onbeforeunload event,

window.onbeforeunload = function (e) {
  console.log('Save data to the localStorage');

  // Return null will disable the prompt
  return null;
};

This way, you can even call your API to save data before user closed the tab.