David Burson
David Burson

Reputation: 3197

is an electron BrowserWindow id guaranteed to be unique for the life of an application?

If my electron app opens and closes lots of BrowserWindows, is each one guaranteed to have a unique id?

So, within a single run of my app, if I open a BrowserWindow and close it, then open a new BrowserWindow: is there any chance the new BrowserWindow will have the same id as the one that I closed?

Upvotes: 1

Views: 565

Answers (1)

pergy
pergy

Reputation: 5531

You can expect unique ID for every instance based on the current source (1.8.4 release or 2.0.0-beta.5)

On the native side BrowserWindow implementation inherits from TrackableObject which actually handles IDs. win.id API looks like this

int32_t Window::ID() const {
  return weak_map_id();
}

ID returned by weak_map_id() is constructed in TrackableObject like this

weak_map_id_ = ++next_id_;
weak_map_->Set(isolate, weak_map_id_, wrapper);

where next_id_ is a static member across trackable instances and is never decreased.

Thus, browser IDs should always keep incrementing during the whole run of your app regardless of deletions.


The following silly example confirms the behavior

const { app, BrowserWindow } = require('electron')
let win = null
app.once('ready', () => {
  setInterval(() => {
    win = new BrowserWindow()
    console.log(win.id)
  }, 1000)
  setInterval(() => {
    win.destroy()
  }, 2100)
})

Upvotes: 1

Related Questions