How to detect user navigation type before or during Page_Load

I have a .NET Framework application. I want to redirect the user back to some page anytime when they arrive certain pages by clicking on back or forward buttons of the browser. I’ve found a solution using JavaScript like below. (This is just a simple example, I’ll map what pages should be redirected from what URL.)

if(is_safe(window.location.href))
    return;
if (window.performance.getEntriesByType("navigation")[0].type === "back_forward")
    window.location.href = "/Home.aspx";

That works. However I want to avoid the entire Page_Load event, because many pages has Page_Load event that actually post database changes (I know… This is bad). Also, even if this is not the case, it will be nice to avoid loading unnecessary data if I know I will redirect the user to another page anyway.

I think it is impossible to run such javascript before the Page_Load event because it’s triggered before the page is even responded and rendered to the user. My question is: Are there other ways to redirect the user away if the user arrives the page using back or forward button before or during Page_Load?

“Not possible” is also an answer. I’ll just move on and modify those problematic PageLoad events whenever I have time.


EDIT: I didn’t redirect the user from source when they click on the back button because it is either impossible or very inconsistent. I’ve tried and simply couldn’t make it work. At some point when I haven’t figure out this JavaScript solution, I’ve even tried to redirect the user twice, but wouldn’t work because browsers skips the redirect and post when back button clicked. If it is possible, I would be happy to be corrected! We did comply the PRG pattern to avoid double submit, but I don’t think it’s relevant in this case.

  • Are you just looking for page lifecycle events that occur before Page_Load? Like Page_Init?

    – 




  • I’m looking for a way to access the user navigation type before or during Page_Load. I can’t figure out how to get the user navigation type in Page_Init as well.

    – 




  • Ah, I see. I’d be surprised if that information is even sent to the server, since the server doesn’t really need to know it. Taking a step back, what is the actual underlying goal here? Why do you need to know the “navigation type” at all? This sounds like an XY Problem.

    – 

  • Thanks for pointing out! I might not need to. I want to navigate the user away if they click on the back or forward button to arrive a certain page.

    – 




  • If that’s truly needed then it sounds like it would need to happen client-side.

    – 

Leave a Comment