Home > Mobile >  Can I detect if using Next.js router.back() will leave my site and do a router.push('/') i
Can I detect if using Next.js router.back() will leave my site and do a router.push('/') i

Time:06-06

I currently have a "go back" link on a page that currently uses router.back() in the onClick handler to return to the previous page, which normally works if the current page was navigated to within my site, but if the page was navigated to directly (say, via a bookmark or a pasted URL) then I would like the "go back" link to do a router.push('/') to go back to my home page instead. I don't know how to determine if the previous browser history URL is outside my site to do the router.push() instead of the router.back(). Anyone have any suggestions?

CodePudding user response:

You can check out document.referrer and check that the URL's hostname matches yours. If it does, you can safely use router.back(). If it doesn't, you can use router.push('/').

  • Related