node打开谷歌浏览器,并监听关闭

248 阅读1分钟
    openSoftware(software = 'chrome.exe', win) {
        import('chrome-launcher').then(async (ChromeLauncher) => {
            const chrome = await ChromeLauncher.launch({
                startingUrl: 'https://www.baidu.com',
            }).then(chrome => {
                console.log(`Chrome debugging port running on ${chrome.port}`);
                // 主进程给渲染进程发送消息
                win.webContents.send('softwarePid', chrome.port);
                // 监听 Chrome 进程的 exit 事件
                chrome.process.on('exit', () => {
                    console.log('Chrome 浏览器已关闭');
                    win.webContents.send('processClose', chrome.port);
                });
            })
        })
    }

  • cnpm i chrome-launcher引入npm包
  • ChromeLauncher.launch({ startingUrl: 'https://www.baidu.com', }) 可以打开谷歌浏览器,launch方法参数是对象,里面是chrome的可配置参数
  • chrome.process.on('exit' 可以监听谷歌浏览器退出事件,手动关闭浏览器会进入回调