electron: document.hasFocus is incorrect if browser window is loaded/refreshed while not visible or unfocused

  • Electron version: 1.3.5
  • Operating system: macOS 10.11.6

document.hasFocus tells you whether the window is blurred or focus. If a BrowserWindow instance is loaded while hidden or unfocused, it will be set to true and it’s not possible to blur it from that state.

I’m currently working around this by briefly showing/focusing the window, then blurring it from a preload script.

var remote = require('electron').remote;

function setupFocus () {
  // If we load/refresh while the window is hidden or blurred, document.hasFocus is wrong
  // We need to first show the window it it's hidden (this is probably ok if a user manually
  // chose to refresh) or give it focus (e.g. if dev tools is open) then blur it again to properly
  // set the document's focus state
  if (!remote.getCurrentWindow().isVisible() || !remote.getCurrentWindow().isFocused()) {
    if (!remote.getCurrentWindow().isVisible()) {
      remote.getCurrentWindow().show();
    } else {
      remote.getCurrentWindow().focus();
    }
    remote.getCurrentWindow().blur();
  }
}

module.exports = setupFocus;

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Comments: 18 (18 by maintainers)

Most upvoted comments

@jwheare gotcha, i’ll check this out this week!