Currently I have a Visualforce page in Lightning Experience that I only want the users to navigate away from in a certain way (via a link). Right now though, I am trying to get the first part of that functionality working, which is preventing navigation. I have been unable to find anything regarding hiding the navigation tabs up top (doesn't solve the problem but would discourage navigation at least), and the next avenue I've been looking toward is some sort of alert that pops up when the user tries to leave and prevents them from doing so.

The best I got working was an onblur event with modified code from this forum post:

        window.onblur = function () { 
            confirm('Are you sure you want to leave the page?')

Which, of course, only works the first time and won't work again unless you click back into the Visualforce page. I attempted to use the code in this question but no dice.

Is there any way to accomplish this, either through JavaScript or some other means?

1 Answer 1


Use onbeforeunload to handle this situation:

  (event) => (
    (event.returnValue = "Are you sure you want to leave?")

However, the user will always still have a choice to leave or not. You cannot force them to follow your rules. Your app must be prepared to have your user try to break it in unexpected ways.

  • This unfortunately did not fire for me (I put it in script tags in the beginning of the body). Commented Sep 7, 2021 at 11:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .