Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

339
Views
How to do some action and delay browser back (mobile back button)?

I have this use case: One page with two subpages under a hashrouter

for example

domain.com/post/1
domain.com/post/1#details

in the #details hash route I want to listen to "back button clicks" and do one api call to update the post before page closes.

During this time want to show a spinner, then after api call is done let browser finish the window.history.back (back button logic)

Is that possible, and how ?

I am trying this now with partial success. I am using React framework with NextJS and have following code inside one component

    useEffect(() => {
        async function onPopState(e: PopStateEvent): Promise<void> {
            return new Promise((resolve) => handleWantToClose(resolve));
        }

        window.addEventListener('popstate', onPopState);
        return () => {
            window.removeEventListener('popstate', onPopState);
        };
    });

In the above snippet handleWantToClose is called fine when clicking back navigate browser button (or mobile back button ios/android)

Thing is that I cannot delay the pop state. It does not wait for the promise to finish resolve.

handleWantToClose funcion is just doing one api call, then calling the resolve function.

Any idea ? This would be extremely useful to provide great user interface for the website to the mobile users especially that use back button a lot to navigate websites.

Other things I tried

  e.preventDefault();
  e.stopPropagation();
  e.stopImmediatePropagation();

on my popstatelistener, then after api call was done, triggered window.history.back() manually but did not work.

The popstate event is not cancellable.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!