universal-router icon indicating copy to clipboard operation
universal-router copied to clipboard

How to implement onLeave logic with this router?

Open Stupidism opened this issue 7 years ago • 1 comments


Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Stupidism avatar Jun 07 '17 22:06 Stupidism

First of all you need to have a common onclick handler for <a> tags, then you may execute any code and after that prevent default behavior depending on the application state or continue.

function handleLinkClick(event) {
  // "before leave" code here

  if (condition) { // block?
    event.preventDefault(); // block transition
  } else {
    // continue
  }
}

Demo: https://jsfiddle.net/frenzzy/skgj8bd5/

If you are using History module, you can use its API:

history.block((location, action) => {
  // "before leave" code here
});

unblock();

Note that when user leaves the website completely you can use only window.onbeforeunload

frenzzy avatar Jun 08 '17 13:06 frenzzy