使用Electron / Node.js,如何检测macOS上所有已安装的浏览器? [英] Using Electron / Node.js, how can I detect all installed browsers on macOS?
问题描述
我正在尝试找到一种方法来列出我的macOS Electron应用程序中所有已安装的Web浏览器。最好的方法是什么?或者...我很高兴维护可能的浏览器列表,但需要一种方法来检查它们是否存在。
I'm trying to find a way to list all installed web browsers in my macOS Electron app. What would be the best way to do this? Or... I'm happy to maintain a list of possible browsers but need a way to check they are present.
推荐答案
您需要创建子进程,该子进程将执行命令以接收当前安装的应用程序。幸运的是,macOS提供了 system_profiler 实用程序,甚至更好,它允许通过 -xml
参数导出XML。但是请注意,到目前为止,它并不是最快的功能。
You'll need to create a child process which executes a command to receive the currently installed applications. Luckely macOS offers the system_profiler utility for doing so and even better it allows XML export via the -xml
argument. But be aware it is by far not the fastest function.
您需要从子进程回调中获取缓冲区块,将其编码为utf-8,然后解析XML字符串,例如 xml2js
。之后,可以简单检查是否检查浏览器的属性。
You'll need to get the buffer chunks from the subprocess callback, encode it as utf-8 and then parse the XML string through something like xml2js
. After that it is a simple check of the property of the browser is checked or not.
Will Stone更新的代码
Updated code by Will Stone
import jp from 'jsonpath' // for easier json traversal
import { spawn } from 'child_process'
import parser from 'xml2json'
const sp = spawn('system_profiler', ['-xml', 'SPApplicationsDataType'])
let profile = ''
const browsers = [
'Brave',
'Chromium',
'Firefox',
'Google Chrome',
'Maxthon',
'Opera',
'Safari',
'SeaMonkey',
'TorBrowser',
'Vivaldi'
]
sp.stdout.setEncoding('utf8')
sp.stdout.on('data', data => {
profile += data // gather chunked data
})
sp.stderr.on('data', data => {
console.log(`stderr: ${data}`)
})
sp.on('close', code => {
console.log(`child process exited with code ${code}`)
})
sp.stdout.on('end', function() {
profile = parser.toJson(profile, { object: true })
const installedBrowsers = jp
.query(profile, 'plist.array.dict.array[1].dict[*].string[0]')
.filter(item => browsers.indexOf(item) > -1)
console.log(installedBrowsers)
console.log('Finished collecting data chunks.')
})
初始代码:
const { spawn } = require('child_process');
const parser = new xml2js.Parser();
const sp = spawn('system_profiler', ['-xml', 'SPApplicationsDataType']);
sp.stdout.on('data', (data) => {
parser.parseString(data, function(err, result){
console.log(result)
});
});
sp.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
sp.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
这篇关于使用Electron / Node.js,如何检测macOS上所有已安装的浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!