Can Node.js invoke Chrome?

后端 未结 8 1414
长发绾君心
长发绾君心 2021-02-04 09:54

Is it possible for Node.js running on a desktop to spawn a Chrome Browser window? I would like to start a Chrome Browser providing the window size and location when Node.js rece

相关标签:
8条回答
  • 2021-02-04 10:09

    On MacOSX

    var childProc = require('child_process');
    childProc.exec('open -a "Google Chrome" http://your_url', callback);
    //Or could be: childProc.exec('open -a firefox http://your_url', callback);
    

    A bit more:

    • Use "open -a" with the name of your app from /Applications and append your args
    • callback function is called with the output after completion
    • Link to API: https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
    0 讨论(0)
  • 2021-02-04 10:15

    This can be done using open npm package.

    app.listen(PORT, (err) => {
      if (err) console.log(err);
      else open(`http://localhost:${PORT}`, { app: "google chrome" });
    });
    

    We can specify any browser in second parameter with open function.

    0 讨论(0)
  • 2021-02-04 10:17
    var exec = require('child_process').exec
    
    exec('open firefox www.google.pt' , function(err) {
    if(err){ //process error
    }
    
    else{ console.log("success open")
    }
    
    })
    

    This opens firefox in google page from a nodejs script, for chrome should be the same

    0 讨论(0)
  • 2021-02-04 10:20

    With opn:

    const opn = require('opn');
    opn('http://siteurl.com/', {app: ['google chrome']});
    
    0 讨论(0)
  • 2021-02-04 10:22

    I open a new firefox tab on windows here: https://github.com/Sequoia/FTWin/blob/master/FTWin.n.js

    The most salient portion:

    var cp = require('child_process'),
        url_to_open = 'http://duckduckgo.com/';
    
    cp.spawn('c:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe', ['-new-tab', url_to_open]);
    

    Note:

    1. Passing the full path of firefox to child_process.spawn
    2. Escaping of slashes
    3. Passing switches/arguments to firefox.exe: passed as the second parameter of cp.spawn as an array (one entry per switch).

    This call is the equivalent of typing "c:\Program Files (x86)\Mozilla Firefox\firefox.exe" -new-tab http://duckduckgo.com at the windows command line.

    For chrome you'd want something like D:\Users\sequoia\AppData\Local\Google\Chrome\Application\chrome.exe --new-tab http://duckduckgo.com/ I'll let you work out the child_process version on your own ;)

    References:

    http://peter.sh/experiments/chromium-command-line-switches/

    http://nodejs.org/docs/v0.3.1/api/child_processes.html

    0 讨论(0)
  • 2021-02-04 10:26

    Node can only do that if you call a UNIX / Windows command, so sys shell command only.

    0 讨论(0)
提交回复
热议问题