Coder Social home page Coder Social logo

electron-eval's Introduction

electron-eval

npm version Build Status Dependency Status

Run code inside a hidden Electron window

electron-eval gives you a way to access a headless browser (Chromium) from Node.js. This can be useful for testing browser-specific code, or using web APIs that are in browsers but not yet in Node (such as WebRTC).

Running on Headless Machines

This module runs without any prior setup on non-headless machines.

To run on a headless Linux server, you'll need the xvfb package:

$ sudo apt-get install xvfb

To run in Travis CI, see the .travis.yml file for this repo as an example of how to install the necessary packages.

Usage

npm install electron-eval

var electronEval = require('electron-eval')

// create new electron instance
var daemon = electronEval()

daemon.eval('JSON.stringify(window.location.href)', function (err, res) {
  console.log(err, res)
  // prints 'null file:///Users/mappum/Projects/electron-eval/index.html'
})

// use es6 multiline strings for longer pieces of code
daemon.eval(`
  var i = 0
  i += 10
  i -= 2
  i
`, (err, res) => console.log(err, res))
// prints 'null 8'

// close the window when you are done with it
// note that this happens automatically after the node process ends
daemon.close()

Methods

var daemon = electronEval([opts])

Creates a new hidden Electron instance. This may be called many times to create many windows, but beware that Electron uses a lot of resources.

opts may be an object containing the following keys:

{
  headless: Boolean // default: false
  // whether or not we should run in headless mode (using Xvfb)
  xvfb: Object // default: {}
  // configures specific xvfb options (see: https://github.com/Rob--W/node-xvfb#usage)
  timeout: Number // default: 10000
  // how often to check if the parent node process is still
  // alive (in milliseconds). If the node process is killed,
  // Electron will close
}

daemon.eval(code, [opts], [callback])

Evaluates the code string in the Electron window, and calls callback(error, result). If callback is not provided and the eval causes an error, the daemon will emit an error event.

The opts object may contain:

{
  mainProcess: Boolean // default: false
  // if true, the code will be evaluated in the Electron main process, rather than the Electron window
}

Note that you may need to stringify the result value with JSON.stringify() so it will be sent properly across processes.

If daemon.eval() is called before the daemon has emitted its ready event, the code will be put in a queue and evaluated once the daemon is ready.

daemon.close()

Closes the Electron process and releases its resources.

Note that the Electron process will automatically terminate when the node process exits, so this may not be necessary.

window.send(event, message)

This method is implemented inside the Electron window, so it may be called from code evaluated by the daemon. It sends a message to the node process, which causes an event named event to be emitted on the daemon object.

This is useful when you need the browser window to send async messages to the node process.

Example:

daemon.on('test', function (arg) {
  console.log('got message: ' + arg)
})
daemon.eval('window.send("test", 123)')

// the node process will print "got message: 123"

Properties

daemon.child

A handle to the Electron daemon's process (of type child_process.ChildProcess).

Events

- ready

Emitted by daemon when the Electron window has been set up and is ready to eval code.

- error

Emitted by daemon when daemon.eval() evaluates code that throws an error, but no callback is provided.

Environment Variables

HEADLESS

Setting this variable to true also allows the module to go into headless mode.

Related

electron-spawn

electron-eval's People

Contributors

autarc avatar daviddias avatar diegorbaquero avatar feross avatar greenkeeperio-bot avatar mafintosh avatar mappum avatar yciabaud avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

electron-eval's Issues

Failure with Xvbf not installed OSX

Electron eval throws on OSX. I am on node 6.2.1 and OSX 10.10. [email protected] is installed with the package.

Ran unit tests with the following traceback:

  not ok Error: Could not start Xvfb: "Xvfb is not installed or is not in your $PATH".  The "xvfb" package is required to run "electron-eval" on Linux. Please install it first ("sudo apt-get install xvfb").
    at:
      line: 9
      column: 10130
      file: lib/index.js
    stack: |
      lib/index.js:9:10130
      ChildProcess.onError (node_modules/headless/index.js:67:9)
      _combinedTickCallback (internal/process/next_tick.js:74:11)
      process._tickCallback (internal/process/next_tick.js:98:9)
    test: xvfb has started and shutdown
    message: >-
      Error: Could not start Xvfb: "Xvfb is not installed or is not in your $PATH". 

      The "xvfb" package is required to run "electron-eval" on Linux. Please install
      it first ("sudo apt-get install xvfb").
    source: >
      function _inherits(subClass, superClass) { if (typeof superClass !==
      "function" && superClass !== null) { throw new TypeError("Super expression
      must either be null or a function, not " + typeof superClass); }
      subClass.prototype = Object.create(superClass && superClass.prototype, {
      constructor: { value: subClass, enumerable: false, writable: true,
      configurable: true } }); if (superClass) Object.setPrototypeOf ?
      Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
      }

  not ok Error: test after end() was called
    at:
      line: 7
      column: 7
      file: test.js
      function: process.on
    stack: |
      process.on (test.js:7:7)
      processEmit (node_modules/nyc/node_modules/signal-exit/index.js:146:32)
    test: catch errors
    count: 1
    plan: 0
    message: 'Error: test after end() was called'
    source: |
      t.error(err, 'caught error')

total ............................................... 24/26


  24 passing (8s)
  2 failing

---------------------------|----------|----------|----------|----------|----------------|
File                       |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
---------------------------|----------|----------|----------|----------|----------------|
 electron-eval-master/     |      100 |      100 |      100 |      100 |                |
  index.js                 |      100 |      100 |      100 |      100 |                |
 electron-eval-master/lib/ |    84.25 |    67.69 |    77.78 |    85.57 |                |
  index.js                 |    84.25 |    67.69 |    77.78 |    85.57 |... 132,136,140 |
---------------------------|----------|----------|----------|----------|----------------|
All files                  |    84.38 |    67.69 |    77.78 |    85.71 |                |
---------------------------|----------|----------|----------|----------|----------------|

Parser error in electron-eval

Hello!

I get this error on use electron-webrtc in webtorrent-hybrid

teste

Aparently, is an error in newline-json dependencie. code:

Parser.prototype._transform = function(chunk, encoding, cb) {
this._buffer += this._decoder.write(chunk);
var lines = this._buffer.split(/\r?\n/);
this._buffer = lines.pop();
for (var l = 0; l < lines.length; l++) {
var line = lines[l];
try {
var obj = JSON.parse(line);
this.push((obj === null || obj === undefined) ? false : obj);
} catch (err) {
var context = lines.slice(l).join('\n')+'\n'+this._buffer;
er = new Error(err.message+' in '+JSON.stringify(context));
this.emit('error', er);

return;
}
}
cb();
};

My O.S is Windows Server 2008. Is compatible?

@mappum

Handle child process crashing

The context for this is that I've been trying to use electron-webrtc on a machine running Amazon EC2 Linux. The electron process is crashing because it can't find a library. However, this doesn't result in electron-eval emitting an error.

I think that I can fix this by listening for the close event from the child process and then emitting an error event if the status code is not 0. What's a good way to display the error? We could just pipe stderr from the child process to stderr for the main Node JS process for starters.

Headless environment issue

Running the example code;

var electronEval = require('electron-eval')

// create new electron instance 
var daemon = electronEval()

daemon.eval('JSON.stringify(window.location.href)', function (err, res) {
  console.log(err, res)
  // prints 'null file:///Users/mappum/Projects/electron-eval/index.html' 
})

In a headless environment (inside docker run node:argon) yields;

events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: write EPIPE
    at exports._errnoException (util.js:870:11)
    at WriteWrap.afterWrite (net.js:769:14)

At version 0.7.6.

Update `electron`

Description

The Electron version specified in package.json is 1.8.8. That version of Electron doesn't have any darwin-arm64 builds (any M1 mac).

Can we upgrade to atleast Electron 11? That's the most recent package to support arm builds.

Replicate Issue

  1. Initiate a new npm project (npm init -y)
  2. Install electron-eval with pnpm:
❯ npm i electron-eval
npm WARN deprecated [email protected]: This package is broken and no longer maintained. 'mkdirp' itself supports promises now, please switch to that.
npm WARN deprecated [email protected]: this library is no longer supported
npm WARN deprecated [email protected]: Please upgrade to latest, formidable@v2 or formidable@v3! Check these notes: https://bit.ly/2ZEqIau
npm WARN deprecated [email protected]: This module has been superseded by the multiformats module
npm WARN deprecated [email protected]: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated [email protected]: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated [email protected]: This module has been superseded by the multiformats module
npm WARN deprecated [email protected]: This module has been superseded by the multiformats module
npm WARN deprecated [email protected]: This module has been superseded by the multiformats module
npm WARN deprecated [email protected]: This module has been superseded by the multiformats module
npm ERR! code 1
npm ERR! path /private/tmp/owl/node_modules/electron
npm ERR! command failed
npm ERR! command sh -c node install.js
Downloading electron-v1.8.8-darwin-arm64.zip
npm ERR! Error: GET https://github.com/electron/electron/releases/download/v1.8.8/electron-v1.8.8-darwin-arm64.zip returned 404
npm ERR! /private/tmp/owl/node_modules/electron/install.js:47
npm ERR!   throw err
npm ERR!   ^
npm ERR!
npm ERR! Error: Failed to find Electron v1.8.8 for darwin-arm64 at https://github.com/electron/electron/releases/download/v1.8.8/electron-v1.8.8-darwin-arm64.zip
npm ERR!     at Request.<anonymous> (/private/tmp/owl/node_modules/nugget/index.js:169:61)
npm ERR!     at Request.emit (node:events:527:28)
npm ERR!     at Request.onRequestResponse (/private/tmp/owl/node_modules/request/request.js:1059:10)
npm ERR!     at ClientRequest.emit (node:events:527:28)
npm ERR!     at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:631:27)
npm ERR!     at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
npm ERR!     at TLSSocket.socketOnData (node:_http_client:494:22)
npm ERR!     at TLSSocket.emit (node:events:527:28)
npm ERR!     at addChunk (node:internal/streams/readable:315:12)
npm ERR!     at readableAddChunk (node:internal/streams/readable:289:9)

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/animcogn/.npm/_logs/2022-07-27T16_18_25_596Z-debug-0.log

Support proxy settings or run code in main process

I am trying to add proxy support when using electron-wrtc (in webtorrent) but I don't think it's possible right now with electron-eval.

I believe it could be useful to add a way to set the settings or event better to allow running code in the electron main process.

Maybe we could add a new function to eval code in the main process and wrap the code in a structure like : { target: "renderer|main", code: "..." } in order to make the difference in the deamon.

What do you think ? I can send a PR in this way if you like.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.