theKashey / react-focus-lock

It is a trap! A lock for a Focus. 🔓
MIT License
1.27k stars 67 forks source link

Add an `onError` callback for when focus fighting is detected #247

Closed SpaceK33z closed 1 year ago

SpaceK33z commented 1 year ago

Use case: I'm making a chrome extension where we attach a <div /> to the end of the body and use your focus lock package to force focus. In some cases the webpage itself is also using a focus lock package, react-focus-lock detects this and shows a "Focus fighting detected" message in the logs.

I can't find a way to access when this happens (unless I'm mistaken), basically I want this:

<FocusLock onError={() => console.log('Focus fighting detected')}></FocusLock>

Is it correct that this is not possible at the moment?

theKashey commented 1 year ago

I got you. Wiring up this functionality can be not very straight forward as it just a safety net, not really expected to be used. So far what you can do - set a timer in onActivation (triggers right before moving focus) and check if focus is within your div

<div ref={ref}>
  <FocusLock 
     onActivation={() => setTimeout(() => 
        ref.current.contains(document.activeElement) 
        ? console.log('active')
        : console.log('failed'))
     }
  >...</FocusLock>
SpaceK33z commented 1 year ago

Thanks so much! Had a similar trick with document.activeElement but your solution is cleaner.