在 Electron 中获取渲染器进程 ID

Acquire renderer process id in Electron

在 Electron 中,渲染器进程的 pid 由

公开
processId = require('remote').getCurrentWindow().getProcessId()

然而,这在最近的版本中不再有效 (1.4.x、1.5.x、1.6.x)。

是否有任何其他方法来获取渲染器进程的 pid,即 Windows 的 pid?

以下稍作修改的版本适合我

require('electron').remote.getCurrentWebContents().getProcessId()

示例:

const { app, BrowserWindow } = require('electron')

app.once('ready', () => {
  var br = new BrowserWindow()
  br.once('focus', () => {
    br.webContents.openDevTools({detach:true})
    br.webContents.executeJavaScript(`
      const remote = require('electron').remote
      console.log(remote.getCurrentWebContents().getProcessId())
    `)
  })
  br.loadURL('http://google.com')
})

1.4.13 测试

奇怪的是,在 Darwin 或 Linux Mint 上,使用 Electron 1.6.7,

require('electron').remote.getCurrentWebContents().getProcessId()

returns 3,对于有效的进程 ID 来说似乎很小。

但是,从渲染器进程来看,

process.pid

returns 正确的渲染器进程 ID,并且

require('electron').remote.process.pid

returns 正确的主进程 ID。

这可以通过使用 Darwin 上的 Activity 监视器应用程序或 Linux Mint 上的系统监视器应用程序来确认。

获取渲染器的 OS pid(不是路由 id)的方法 getOSProcessId() 已添加到 Electron v1.7.1. Here is the original pull request

require('electron').remote.getCurrentWebContents().getOSProcessId();

从 electron 14 开始,远程模块已经 removed

// Deprecated in Electron 12:
const { BrowserWindow } = require('electron').remote


// Replace with:
const { BrowserWindow } = require('@electron/remote')

// In the main process:
require('@electron/remote/main').initialize()