0

I need help with my authentication flow. I need to know how I can go to the opened tab when I click on the button in the email when I already opened tab with the same origin?

Suppose I have a tab with the URL https://example.come currently opened in my browser. then I click the button in my email which href to https://example.come?token=sss. I want to go to the opened tab rather than opening a new tab. is it achievable?

principiorum
  • 528
  • 7
  • 21

1 Answers1

0

You could use localStorage to keep track of opened tabs within your domain.

  • Initialize your localStorage with your list of pages to keep track of and dates from them.
  • Upon clicking on your anchor, update your localStorage.
  • Whenever the anchor is clicked, check your localStorage and make the decision.
  • You cannot redirect to another tab though. It is better to show the message.

const pagesToListen = {
  login: "/login",
}

function createTabListener(route) {
  const key = `$$DOMAIN_${route}`;

  function checkIfOpened() {
    const tabInfo = JSON.parse(localStorage.getItem(key))
    if (tabInfo) {
      // check for the minimum dates required
      if (tabInfo.date < 10) return true;
    } else {
      localStorage.setItem(key, { date: Date.now() });
      return false;
    }
  }

  return checkIfOpened;
}

const loginTabListener = createTabListener(pagesToListen.login);

// on anchor tags

function MyComponent() {
  function handleClick() {
    if(loginTabListener.checkIfOpened()) {
      alert('You login page is opened')
    } else {
      // push to the history
    }
  }

  return (
    <a href="/login" onClick={handleClick} />
  )
}

Prateek Thapa
  • 4,829
  • 1
  • 9
  • 23