3

I want to execute some logic in specific moment(from my LWC) if no Inputs has the focus on my Page.
So I want to know if there is the focus on some input on the page ?
(Logic is executed from an Event Listener on "keypress")

The LWC is a part of managed package, so an idea with enabling Lightning Web Security is not the case.

From JavaScript side, I would use document.activeElement, to achieve this
See next question : How do I find out which DOM element has the focus?

I see that document.activeElement is still available in Locker API Viewer

enter image description here

However I can not access the document.activeElement properties in my LWC.
And If I debug next line

console.log(document.activeElement.toString());

I will get next output

SecureObject: [object HTMLDivElement]{ key: {"namespace":"c"} }

So it looks like Lightning Locker blocks me from seeing the data from document.activeElement.

SecureObject - secure wrapper for an object that is wrapped by Lightning Locker. When you see a SecureObject, it typically means that you don’t have access to the underlying object and its properties aren’t available.

Is there any other way to access document.activeElement ?
Or to find out if some DOM element has the focus ?

Any help will be appreciated,
Thank you

4
  • 2
    Are you using Locker Service? If so, have you tried switching to Lightning Web Security?
    – sfdcfox
    Sep 13, 2022 at 14:37
  • 1
    @sfdcfox Thanks, I have enabled Lightning Web Security and now I can access the document.activeElement properties. However the LWC is included in Managed Package and I can't be sure that Lightning Web Security will be enabled there. Are there any other ways ? Sep 13, 2022 at 15:04
  • 1
    Not necessarily an answer, but try: window.addEventListener('focusin', (event) => { this.activeElement = event.target });; this should allow you to get an event whenever an element is focused. However, it may not always be the value you expect, and it probably still won't work outside your namespace.
    – sfdcfox
    Sep 13, 2022 at 15:28
  • @sfdcfox thanks, However I always get the same result and I can't differentiate which focus is on simple element and which is on input. Ok, I now understand that I have not asked about it. I need to know only when focus is on some of inputs on my page. I updated the question Sep 13, 2022 at 16:49

0

You must log in to answer this question.

Browse other questions tagged .