Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Node.js invoke Chrome?

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 receives an event.

Is sys shell commands only methodology?

like image 224
Bill Christian Avatar asked Nov 10 '11 19:11

Bill Christian


People also ask

Does Chrome use node JS?

Chrome V8 executes JavaScript code. Node. js is built on top of Chrome V8 and is a widely used runtime environment for serverless JavaScript functions.

CAN node JS run in a browser?

js is a server-side JavaScript run-time environment. It's open-source, including Google's V8 engine, libuv for cross-platform compatibility, and a core library. Notably, Node. js does not expose a global "window" object, since it does not run within a browser.

How do you invoke a browser in the node system?

Node allows you to create a child process in four different ways: spawn() , fork() , exec() , and execFile() . We will be using the exec() call to launch a browser in a child process. The exec() call buffers the command's generated output and passes all output to a callback function.

Does node uses the same engine as Chrome?

Node uses the same JS "engine" that runs chrome. An engine in this case, is a piece of software that compiles, or "translates" your JS code into machine code; or the 0s and 1s your computer can understand.


2 Answers

Checkout https://www.npmjs.com/package/chrome-launcher:

Launch chrome:

const chromeLauncher = require('chrome-launcher');

chromeLauncher.launch({
  startingUrl: 'https://google.com'
}).then(chrome => {
  console.log(`Chrome debugging port running on ${chrome.port}`);
});

Launching headless chrome:

const chromeLauncher = require('chrome-launcher');

chromeLauncher.launch({
  startingUrl: 'https://google.com',
  chromeFlags: ['--headless', '--disable-gpu']
}).then(chrome => {
  console.log(`Chrome debugging port running on ${chrome.port}`);
});

chrome-launcher opens a remote debugging port so you can also control browser instance using the DevTools protocol.

Puppeteer is another way to launch Chrome and interact with it using high level APIs.

like image 72
ebidel Avatar answered Sep 20 '22 13:09

ebidel


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
like image 39
MaxRd Avatar answered Sep 18 '22 13:09

MaxRd