Skip to content

.focus() does not fire focus events if window is not focussed #553

Closed
@FritsvanCampen

Description

@FritsvanCampen

Browsers (confirmed in Chrome/Firefox) will not dispatch focus events when the window is not focused when calling .focus().
Here is a codepen that demonstrates this behavior: https://codepen.io/fritsvancampen/pen/OJbPaLX

This becomes a problem if you're using a test-runner that uses a real browser to test (such as Karma) and you're running tests locally, or testing with more than one browser at once (ie Chrome and Firefox). Only one browser window can have focus at a time so your code under test is going to behave differently. You can imagine the kind of debug-hell you end up in, it's an actual Heisenbug!

I understand that if you're using a headless browser or a mocked browser this is not an issue.

Is this a use-case that this library wants to support?


I have been tinkering with a workaround but I haven't found a perfect solution but perhaps we don't need a perfect solution.

Instead of calling .focus() you can fire the focus events manually (with dispatchEvent/fireEvent), and set the activeElement. However the latter doesn't get picked up by CSS which might be a problem because of :focus rules.

Another possibility is to fire the focus events and call .focus() (to move the activeElement). This has the same problem: it also doesn't trigger :focus CSS-rules. This also generates duplicate events, which is acceptable for my use case.

Trying to retro-actively apply the workaround to this library is a bit of a headache so an integrated solution would be nice to have. I would find it acceptable to activate this workaround behavior through some kind of config.

Here is a codepen with the workaround: https://codepen.io/fritsvancampen/pen/VwmYVQe


I would offer a PR but I can't seem to get the test-suite running (detects 0 tests).

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs specificationThe desired behavior is not defined yet

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions