Skip to content

Add 'focus' & 'blur' events to BrowserView/WebContents #22201

Closed

Description

@aziz512

Preflight Checklist

  • I have read the Contributing Guidelines for this project.
  • I agree to follow the Code of Conduct that this project adheres to.
  • I have searched the issue tracker for a feature request that matches the one I want to file, without success.

Problem Description

When working with BrowserViews, there's no way to listen to focus changes on either BrowserView itself or its WebContents.

Proposed Solution

On BrowserWindow, there are focus and blur events. The same events need to be emitted on BrowserView/WebContents.
i.e. :

browserView.on('focus', () => {
    // view is focused, do stuff
});

or

browserView.webContents.on('focus', () => {
    // contents are focused, do stuff
});

Alternatives Considered

I can't think of a good way of working around this lack of functionality

Activity

  1. Lee182 commented on May 7, 2020

    @Lee182

    Hello I too would like the same event emitted. To keep track of the active. Though for my use case (applying a global keyboard shortcut to tab) I've gotten around with this.

    const { webContents } = require('electron')
    webContents.getFocusedWebContents()
  2. mckravchyk commented on Nov 13, 2021

    @mckravchyk
    Contributor

    It won't help with every scenario, but you can have a quasi-focus event by tapping to pointerdown.

    Minimal example:
    (add to preload, and ensure preload is also in iframes (option webPreferences.nodeIntegrationInSubFrames: true):

    window.addEventListener('pointerdown', () => { ipcRenderer.send('focus'); });
    

    I say quasi-focus event because it will be emitted even when the webContents are already focused (but sometimes it's good enough). You could also try use it and implement tracking of which webContents are currently focused and put it together to emulate a real focus event. And if you use webContents.focus() - it would have to be taken into account as well.

    Still, a built-in implementation would surely be appreciated :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions