简体   繁体   中英

How to detect Installed Browsers on a Mac Machine using Node.js?

Need a node-js program which can detect the Installed Browsers(or Applications) on the local machine

I stumbled upon this question for a few days and found the following links:-

  1. Using Electron / Node.js, how can I detect all installed browsers on macOS? [Takes time; only gave me the names of the browser, and if I needed path & version, the headers were somehow incorrect to process]
  2. https://github.com/litixsoft/karma-detect-browsers [Seems legit, couldn't use]

Then I came up with my own version. This assumes that the browser/application is installed in the /Application directory.

var {
  spawn
} = require('child_process');

const fs = require("fs"); // Or `import fs from "fs";` with ESM


function detectAllBrowsers(callback) {
  const browsers = [
    'Chromium',
    'Firefox',
    'Google Chrome',
    'Opera',
    'Safari',
    'TextEdit'
  ]

  var detectedBrowsers = [];
  var promises = [];

  browsers.forEach(function(browserName, index) {
    // /Applications/Google\ Chrome.app/Contents/Info.plist
    var path = '/Applications/' + browserName + '.app';
    var aPromise = new Promise(function(resolve, reject) {
      if (fs.existsSync(path)) {
        var aBrowser = {
          name: browserName,
          path: path
        }

        var sp = spawn('/usr/libexec/PlistBuddy', ['-c', 'print :CFBundleShortVersionString', path + '/Contents/Info.plist']);
        sp.stdout.setEncoding('utf8')
        sp.stdout.on('data', data => {
          aBrowser.version = data.trim();
        });

        sp.on('close', code => {
          detectedBrowsers.push(aBrowser);
          resolve('done');
        });
      } else {
        resolve('done');
      }
    });

    promises.push(aPromise);
  });

  Promise.all(promises).then(data => {
    callback(detectedBrowsers);
  });
}

detectAllBrowsers(function(detectedBrowsers) {
  console.log(detectedBrowsers);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM