holla
holla

Reputation: 161

Detect previous path in react router if i came from an outside application?

I am using react router. I want to detect the previous page (outside app example: coming from gmail to my application) from where I am coming from. I have the router in my context. But, I don't see any properties like "previous path" or history on the router object. How do I do it?

example 2: user places an order we send them an email confirmation via email where onclick on view-order-details they are navigated back to our web app, now how to detect which link they came from?

Here's another context to understand better

I have to implement a back button in my web app, when user comes from email to my webapp he's navigated to https://example.com/orders/{orderID} directly and if i just use props.history.goBack it'll go back to email page. But i want to user to be navigated to https://example.com/dashboard.

Now you might say use props.history.push('/dashboard') this will become static value. if user is navigated internally(not coming from email or external page) from dashboard->all-orders->orders/{orderID} on click of back button should be navigated to dashboard->all-orders page and not to dashboard.

Upvotes: 4

Views: 2391

Answers (1)

Mastacheata
Mastacheata

Reputation: 2061

To read the history in React-Router use the history object that's passed along with the routeComponentProps or the useHistory hook.

But that won't give you what you're looking for either:

  1. There is no way to read entries in the browser history. Browsers simply don't expose that to JS at the moment. See this entry on the history API on MDN
  2. In order to detect which site a visitor came from you can check the referrer. document.referrer on MDN

Example for a button that goes back one step in history for internal referrers, but goes to the dashboard if the site was loaded from a bookmark or external link:

button.onclick - () => {
  if (document.referrer && document.referrer.length > 0 && document.referrer.startsWith('https://yoursite.com')) {
    // user came from an internal link
    window.history.goBack(1);
  }
  else {
    // user came from a bookmark or an external link
    window.location = 'https://yoursite.com/dashboard';
  }
};

The HTML5 history allows you to go back to an arbitrary point in history, but you can't know the details about that point in history. You can only go back to it by a numerical index.

Upvotes: 4

Related Questions