'Change URL in Browser Detection

Hello I used UAParser as an identifier to detect what browser is used.

for example I have a window.location.href of "localhost:8000/"

when I reload and detect that it's from chrome it should change to "localhost:8000/#chrome

This is my code in doing it.

const [messenger, setMessenger] = useState(window.location.replace(`${window.location.href}/#chrome`))

let parser = new UAParser()
let browser = parser.getBrowser()
let browserName = browser.name

useEffect(() => {
 if (browserName.includes("Chrome")) {
   setMessenger(messenger)
   setOpen(true)
 }
}, [])

but what's happening to me is it's continuously refreshing the page and the result is localhost:8000/#chrome but keeps on refreshing.

sometimes what happens is localhost:8000/#chrome/#chrome/#chrome/#chrome

may I know what is missing or wrong in my implementation.

what I simply want is just add #chrome to be localhost:8000/#chrome



Solution 1:[1]

Try to also check whether you already changed your location to stop refreshing:

if (browserName.includes("Chrome") && !location.href.includes("#chrome"))

Solution 2:[2]

You don't need a useState for (in your case messenger), just make it in the component constructor, ex:

const MyComponent = () => {
  const [open, setOpen] = useState(false) // ? your default open value
  const parser = new UAParser()
  const browser = parser.getBrowser()
  const browserName = browser.name

  useEffect(() => {
   if (browserName.includes("Chrome")) {
     window.location.replace(`${window.location.href}/#chrome`)
     setOpen(true)
   }
  }, [])
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 asker12743
Solution 2 Normal