Will Stone
Will Stone

Reputation: 4825

Using Electron / Node.js, how can I detect all installed browsers on macOS?

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.

Upvotes: 1

Views: 2947

Answers (1)

Hans Koch
Hans Koch

Reputation: 4481

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.

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.

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.')
})

Initial code:

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}`);
});

Upvotes: 3

Related Questions