Giter VIP home page Giter VIP logo

electron-connect's Introduction

electron-connect Build Status npm version dependency

Utility tool to develop applications with Electron.

Using this in your Node.js scripts (e.g. gulpfile.js), you can livereload your Electron app.

It provides the following features:

  • start (and restart) Electron application.
  • reload renderer processes.
  • stop Electron application.

Install

Use npm:

npm install electron
npm install electron-connect --save-dev

Usage

electron-connect has server and client components. They communicate with each other using WebSocket. The server component manages Electron process and broadcasts reload event to client, and client components reload renderer's resources.

Server

Here is an example creating a server in gulpfile.

'use strict';

var gulp = require('gulp');
var electron = require('electron-connect').server.create();

gulp.task('serve', function () {

  // Start browser process
  electron.start();

  // Restart browser process
  gulp.watch('app.js', electron.restart);

  // Reload renderer process
  gulp.watch(['index.js', 'index.html'], electron.reload);
});

Client

A client can be created in either browser process or renderer process. Note: Please make sure it is not done in both.

  • RendererProcess
<html>
<body>
<!-- build:remove -->
<!-- Connect to server process -->
<script>require('electron-connect').client.create()</script>
<!-- end:build -->
</body>
</html>

Do you want to use this tool for only develop environment ? You can remove the <script> block in your gulpfile using gulp-useref.

  • BrowserProcess
'use strict';

var app = require('app');
var BrowserWindow = require('browser-window');
var client = require('electron-connect').client;

app.on('ready', function () {
  var mainWindow = new BrowserWindow({
    width: 400,
    height: 300
  });
  mainWindow.loadUrl('file://' + __dirname + '/index.html');

  // Connect to server process
  client.create(mainWindow);
});

If you want details, see example/simple.

API References

server.create([options])

  • options Object
  • electron Object. An electron module. Set it If you want to use your forked Electron.
  • useGlobalElectron Boolean. If set, electron-connect uses electron module installed globally (default: false).
  • path String. A path to your package.json file (default: process.cwd()).
  • port Number. WebSocket server port (default: 30080).
  • spawnOpt Object. Options for spawn.
  • logLevel Number. The granularity of the electron-connect logging in your prompt. 0 - warning only, 1 - warning and info only, 2 - all logs (default: 1).
  • stopOnClose Boolean. If set, closing last remaining window stops the electron application.

Returns a new ProcessManager object.

If neither electron nor useGlobalElectron option is set, electron-connect searches for electron module automatically.

  1. First, electron-connect searches electron installed locally.
  2. If not hit, electron-connect uses electron installed globally.

New in version 0.5.x and onwards : Now, ProcessManager's start(), restart() and stop() methods invoke callback with an argument that indicates the state of the electron process, which could be one of the following string values -

  • started
  • restarting
  • restarted
  • stopped

See example/stop-on-close, where you can find sample code that uses stopOnClose option and stopped state to shutdown gulp process gracefully.

Class: ProcessManager

start([args], [callback])

  • args String or Array. Additional arguments used when create a process.
  • callback Function

Starts a server and Electron application process.

restart([args], [callback])

  • args String or Array. Additional arguments used when create a process.
  • callback Function

Kills Electron process if it exsists, and starts new one.

This method is useful for callback of your browserProcess sourcecodes' change event.

reload([ids])

  • ids String or Array. A list of id of target client.

Emit reload event to target clients. Broadcasts reload event to all connected Client object if ids not set. This method does not kill any Electron processes.

This method is useful for callback of your rendererProcess sourcecodes' change event.

stop([callback])

  • callback Function

Kills Electron process and stops server.

on(eventName, callback)

  • eventName String
  • callback Function

Registers an eventhandler that gets invoked when an event is emitted by Client.sendMessage.

broadcast(eventName, [data])

  • eventName String. A message type.
  • data Object. A message data.

Broadcasts an event to all clients.

client.create([browserWindow], [options], [callback])

  • browserWindow Object. Optional, in rendererProcess only. Required, when client is created in browserProcess.
  • options Object
  • port Number. WebSocket server port (default: 30080) that client should connect to.
  • sendBounds Boolean
  • logLevel Number. See server.create([options]).logLevel.
  • callback Function

Creates a new Client object associated with browserWindow and connects to ProcessManager.

The browserWindow should be an Electron browser-window instance. Once a client is created and connected to the server, client can receive events (e.g. reload).

If sendBounds is set (default true), client sends a bounds object when browserWindow moves or resizes. And when ProcessManager.restart() is called, client recovers the bounds stored at server.

Class: Client

id

An identifier of this client. It is a same value browserWindow.id.

on(eventName, callback)

  • eventName String
  • callback Function

Registers an eventhandler that gets invoked, when an event is emitted by ProcessManager.broadcast.

sendMessage(eventName, [data])

  • eventName String. A message type.
  • data Object. A message data.

Emits an event to ProcessManager.

License

MIT

electron-connect's People

Contributors

akashnimare avatar bradzacher avatar farfromrefug avatar josefjura avatar joshball avatar kenpb avatar mweibel avatar quramy avatar samypesse avatar ssreekanth avatar zhuangya 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

electron-connect's Issues

When browser window's bounds are modified in the code, electron restart doesn't use these modified bounds' values when displaying the window.

My gulp task is as follows -

gulp.task('serve', function () {
  var electron = require('electron-connect').server.create({verbose: true});

  // Start browser process
  electron.start();

  // Restart browser process
  gulp.watch(['browser/**/*.js'], electron.restart);

  // Reload renderer process
  gulp.watch(['renderer/index.html', 'renderer/bundle/**/*'], electron.reload);
});

In the browser process's main.js, i have

mainWindow = new BrowserWindow({width: 400, height: 600});
  1. First, when gulp 'serve' task is started, window gets created with 400x600
  2. resize the window by dragging the window corner to 600x800
  3. Now, modify the code with different bound values to trigger electron.restart() as follows -
mainWindow = new BrowserWindow({width: 100, height: 100});

After electron.restart(), I would expect to see the displayed window to have 100x100 bounds. However, it still has 600x800 bounds.

As a result, this forces me to kill electron-connect server process and re-run the gulp 'serve' task, everytime I make any changes to the window's bounds in the code.

cmd line version for use by npm scripts?

Tool looks great but with npm scripts there is really no reason to use gulp anymore. Would you consider creating command line support so it can just be used from a npm like f.x. what I do for a normal nodejs project where I can add a script like this:
start:server": "nodemon --debug bin/lib/start.js",

Electron 1.1 not working

Hi!

I try to use electron-connect with eletron 1.1.1.
My code:

'use strict';

import app from 'app'
import BrowserWindow from 'browser-window'
import {client} from 'electron-connect'

app.on('window-all-closed', () => {
    if (process.platform != 'darwin') {
        app.quit();
    }
});

app.on('ready', () => {
    var mainWindow = new BrowserWindow({width: 500, height: 300});
    mainWindow.webContents.openDevTools();
    mainWindow.loadURL(`file://${__dirname}/client/app.html`);
    client.create(mainWindow);
});

But the window is not created. When I start from console (electron app.js) or create electron application it's open the window.

Any idea?

server.restart() messes up the bounds of the multiple windows, when client.create() is called from browser process.

Steps to recreate the issue

  1. Using the below code, run gulp serve
  2. Now, touch app.js to force server.restart()

Actual Result

Both win1 and win 2 have the same bounds after restart.

Expected Result

win1 and win2 get the original (different) bounds.

Code

app.js

const electron = require('electron');
const {app} = electron;
const {BrowserWindow} = electron;
const {client} = require('../../../');

let win1;
let win2;

function createWindowOne() {
  win1 = new BrowserWindow({width: 200, height: 200, x: 100, y: 120});
  win1.loadURL(`file://${__dirname}/win1.html`);
  win1.on('closed', () => {
    win1 = null;
  });
  client.create(win1);
}

function createWindowTwo() {
  win2 = new BrowserWindow({width: 200, height: 200, x: 300, y: 300});
  win2.loadURL(`file://${__dirname}/win2.html`);
  win2.on('closed', () => {
    win2 = null;
  });
  client.create(win2);
}

function createWindows() {
  createWindowOne();
  createWindowTwo();
}

app.on('ready', createWindows);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (win1 === null) {
    createWindowOne();
  }
  if (win2 === null) {
    createWindowTwo();
  }
});

win1.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body style="background-color: #ff8000;">
    <h1>Window 1</h1>
  </body>
</html>

win2.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body style="background-color: #80ff00;">
    <h1>Window 2</h1>
  </body>
</html>

gulpfile.js

'use strict';

var gulp = require('gulp');
var electron = require('../../../').server.create();

gulp.task('serve', function () {

  // Start browser process
  electron.start();

  // Restart browser process
  gulp.watch('app.js', ['restart:browser']);

  gulp.watch('*.html', ['reload:renderer']);

});

gulp.task('restart:browser', function(done) {
  electron.restart();
  done();
});

gulp.task('reload:renderer', function (done) {
  // Reload renderer process
  electron.reload();
  done();
});

gulp.task('default', ['serve']);

Cannot get electron.reload to do anything

I have been trying to use electron reload but I cannot get it to do anything

gulp.task('serve', ['slm','sass','babel'], function(){
  gulp.watch('./main.js', electron.restart);
  gulp.watch(['./www/**/*'], electron.reload);

  gulp.watch(paths.slm, ['slm']);
  gulp.watch(paths.sass, ['sass']);
  gulp.watch(paths.babel, ['babel']);

  electron.start();
});

after reload electron throws error when resizing or moving window

Hi! I'm using the same code as your example (gulp) to reload electron.
The reloading works great but I'm getting the following error as soon as I move or resize the window

Error: Attempting to call a function in a renderer window that has been closed or released. Function provided here: client.js:82:19.
    at BrowserWindow.callIntoRenderer (/Users/hanche/Desktop/bitbucket/Finished-Setup/node_modules/electron-prebuilt/dist/Electron.app/Contents/Resources/electron.asar/browser/rpc-server.js:189:19)
    at emitOne (events.js:101:20)
    at BrowserWindow.emit (events.js:188:7)

I'm using electron inside angular 2 and in the index.html I'm currently using an relative path to access electron connect (../node_modules/electron-connect), not sure if this causes it? Restarting doesn't throw the issue.

Cheers

BrowserProcess keeps open new window instead of restart

I ran example/simple for test, and the main electron process can't stop.
When app.js is modified, it opened another electron window, instead of "restart" it.
I had to use server.broadcast to tell the client to close itself.

Shouldn't spawn args be prepended and not appended?

I tried to require a node package using the -r argument for electron but it wasn't working. I realized the args were being appended to the spawn after the path but these arguments should be prepended.

Original
this.electronProc = proc.spawn(this.opt.electron, [this.opt.path].concat(args), spawnOpt);

Fix
this.electronProc = proc.spawn(this.opt.electron, args.concat([this.opt.path]), spawnOpt);

If this works for everyone then I can create a pull request with my fix.

Connection refused when not using gulp

Is there any way to check that if server is started then create the client in BrowserProcess?
I got this errors on client.create(window) when i try to run the app without a gulp task.

2017-12-29_01-09-10
2017-12-29_01-09-51

Actual JS logging

I wonder if it makes sense the content's JS logging to also be an option as part of electron-connect. Say you have an option to log JS window content, such as contentLogging:true

socket connection is not terminated on closing window, when client.create() is called from browser process.

Single Window Scenario : This is mostly applicable to OS X, where app.quit() is not called on window-all-closed event (as a result of second bullet point in Step 1 below). On other platforms, app.quit() gets called, which would force close the socket connection.

Multiple Window Scenario : The issue can be seen, when any of the multiple windows is closed.

Steps to recreate the issue

  1. As shown in the code below, make sure the following are done.
  • call client.create() in the browser process (app.js)
  • on app window-all-closed event, make sure app.quit() is not called on OS X.
  • on window close event, set window handle to null.

app.js

'use strict';

var electron = require('electron');
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var client = require('../../').client;

app.on('window-all-closed', function () {
  if (process.platform != 'darwin') {
    app.quit();
  }
});

app.on('ready', function () {
  console.log(process.argv.join(', '));
  console.log('Hello, browser process');
  var mainWindow = new BrowserWindow({
    width: 400,
    height: 300
  });

  mainWindow.loadURL('file://' + __dirname + '/index.html');

  mainWindow.on('closed', function() {
    mainWindow = null;
  });

  client.create(mainWindow);
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Simple example app</title>
</head>
<body>
<h1>Hello, Electron</h1>
<script src="index.js"></script>
</body>
</html>
  1. Run gulp serve command.
  2. Close the window.

Expected Behavior

this.close() gets called and socket is terminated.

Actual Behavior

beforeunload event handler is not getting invoked. Hence, socket doesn't get terminated.

Why start is so slow?

When I start electron-connect with gulp, it take about 30 sec to launch the app:

[13:25:51] Using gulpfile ~/Documents/Projects/myproject/gulpfile.js
[13:25:51] Starting 'start'...
[13:26:17] Finished 'start' after 26 s

I'm under MacOs Sierra, node v6.7.0, gulp v3.9.1, gulp CLI v1.2.1 and electron-connect v0.6.0

Set environment vars

It would be great to be able to set environment variables when running the app, such as NODE_ENV.

This could be in the options of start.

events.js:142 > Unhandled 'error' event

Hi,

I'm novice in electron, node.js and gulp and i have trouble to understand this error :

npm install -g gulp
npm install electron-connect
gulp serve

Return me this :

[20:38:06] Starting 'serve'...
[20:38:06] Finished 'serve' after 2.99 ms
[2015-12-17T19:38:06.381Z] [electron-connect] [server] created and liseten to 30
080
events.js:142
      throw er; // Unhandled 'error' event
      ^

Error: spawn electron ENOENT
    at exports._errnoException (util.js:856:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:179:32)
    at onErrorNT (internal/child_process.js:345:16)
    at nextTickCallbackWith2Args (node.js:455:9)
    at process._tickCallback (node.js:369:17)
    at Function.Module.runMain (module.js:433:11)
    at startup (node.js:141:18)
    at node.js:977:3

gulfile.js

'use strict';

var gulp = require('gulp');
var electron = require('electron-connect').server.create();

gulp.task('serve', function() {

  // Start browser process
  electron.start();

  // Restart browser process
  gulp.watch('main.js', electron.restart);

  // Reload renderer process
  gulp.watch(['index.html'], electron.reload);

});

main.js

'use strict';

var app = require('app');
var BrowserWindow = require('browser-window');
var client = require('electron-connect').client;

var mainWindow;
var mainWindowState = { width: 1024, height: 800 };

app.on('ready', function () {

    mainWindow = new BrowserWindow({
        width: mainWindowState.width,
        height: mainWindowState.height
    });

    mainWindow.loadURL('file://' + __dirname + '/index.html');

    mainWindow.on('closed', function() {
        mainWindow = null;
    });

    // Connect to server process
    client.create(mainWindow);

});

index.html

...
...
...
        <!-- build:remove -->
        <!-- Connect to server process -->
        <script>require('electron-connect').client.create()</script>
        <!-- end:build -->
</body>
</html>

Thanks for your help. :)

yargs fails with latest update

Hello, thanks for working on this great library ๐Ÿ‘

Over the last few days we noticed that yargs did not work correctly anymore. Somehow the --env="production" variable that we pass to electron-connect's start function did not properly set the environment variable anymore.

I was able to reproduce it here, where it works fine with v0.4.5 but it fails with v0.4.7.

Doesn't work with Electron 0.31.0

I was starting new project and used the latest version of Electron (0.31.0) and no content was visible nor were there any errors in the console or the browser view. Just a blank app, but the title is visible. . I'm basically starting with the simple example in the repository. Rolling back to 0.30.5 fixes the problem.

restart() closes the window, but never opens a new one

For me restart() closes the window but never opens a new one. From what I see in the source, in order to respawn the process, logic should enter the if (!this.numClients) {... conditional, but it never does, since numClients is decremented only after the client closes websocket connection and for this to happen, probably process should be killed first.

ProcessManager.prototype.restart = function (args, cb) {
  // ...

  if (typeof cb === 'function') {
    this.restartCallback = cb;
  }

  this.electronState = 'restarting';
  if (this.electronProc) {
    this.info('restarting electron process: ' + this.electronProc.pid);
    if (!this.numClients) {
      this.killProcess(function() {
        this.info('respawning electron process..');
        this.spawn(args, this.opt.spawnOpt);
        this.setStateAndInvokeCallback('restarted', this.restartCallback);
      }.bind(this));
    } else {
      this.killProcess(function() {
        if (this.restartCallback) {
          this.restartCallback(this.electronState);
        }
      }.bind(this));
    }
  }
};

Don't include electron-prebuilt as a dependency

Because electron-prebuilt is a dependency, we are locked to the version hardcoded in electron-connect's package.json, which is currently out-of-date.

If you include it as a peer-dependency (and maybe dev-dependency for development, I'm not sure), it means developers including electron-connect in their package.json are responsible for also including electron-prebuilt, and this gives developers the flexibility of what version to include.

Option to not log "received messages from client"

My machine visibly lags when I move the Electron window around, because so much output is being logged and drawn in my terminal :)

Perhaps in the object passed to server.create, there could be a verbose property?

I'd be willing to do a PR if this is acceptable to the maintainer

stopOnClose option doesn't seem to be working..

I have the following in my gulpfile.js

var electron = require('electron-connect').server.create({ stopOnClose: true });

electron-connect server doesn't stop, when all the client windows are closed. I had to type CTRL-C to force quit the gulp task.

Logs show that electron process is killed. But, the gulp task is still running..

[17:32:03] Starting 'serve'...
[17:32:03] Finished 'serve' after 214 ms
[2016-04-26T00:32:03.359Z] [electron-connect] [server] created and listening on 30080
[2016-04-26T00:32:04.269Z] [electron-connect] [client: 1] connected server
[2016-04-26T00:32:09.277Z] [electron-connect] [server] client (window_id: 1) closed.
[2016-04-26T00:32:09.277Z] [electron-connect] [server] stopping electron process
[2016-04-26T00:32:09.277Z] [electron-connect] [server] killing electron process tree:
[2016-04-26T00:32:09.414Z] [electron-connect] [server] client (window_id: 1) closed.
[2016-04-26T00:32:09.414Z] [electron-connect] [server] stopping electron process
[2016-04-26T00:32:09.414Z] [electron-connect] [server] killing electron process tree:
^C

Could not find a declaration file for module 'electron-connect'

Thank you very much for your very good implementation that works for me! I can reload my electron application, it works really very good! I have only one issue, maybe someone can help... When I strat my project with npm run webpack --config crv/config/webpack.dev.js --watch --progress --color --inline I get following warnings and one error message:
image
from electron main process. I'm working with typescript, my implementation in electron main process looks fine to me and it works:

import { app, BrowserWindow, ipcMain } from 'electron';
import * as path from 'path';
import * as url from 'url';
import { client } from 'electron-connect';

let mainWindow: BrowserWindow | null;

const createWindow = async () => {

    // Create the browser window.
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true
        }
    });

    // and load the index.html of the app.
    mainWindow.loadURL(
        url.format(
            {
                pathname: path.join(__dirname, './index.html'),
                protocol: 'file:',
                slashes: true
            }
        )
    );

    client.create(mainWindow);

};

app.on('ready', createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow();
    }
});

There is only the issue with typescript declaration file for module electron-module and warning messages. How can I get rid of those warning and error messages? There is no type definition for @types/electron-connect. Adding electron-connect.d.ts declaration containing declare module 'electron-connect'; does not help. Please help.

Error: spawn electron ENOENT when running gulp serve

Hey, i get the following error when running gulp serve:

[22:28:13] Starting 'serve'...
[22:28:13] Finished 'serve' after 4.6 ms
[2016-11-15T21:28:13.505Z] [electron-connect] [server] started electron process: undefined
[2016-11-15T21:28:13.506Z] [electron-connect] [server] created and listening on 30080
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: spawn electron ENOENT
    at exports._errnoException (util.js:856:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at nextTickCallbackWith2Args (node.js:478:9)
    at process._tickCallback (node.js:392:17)
    at Function.Module.runMain (module.js:432:11)
    at startup (node.js:141:18)
    at node.js:1003:3

i am running ubuntu, node v5.4.0, gulp 3.9.1, npm 4.0.1

can someone help me out here?

reload not working with gulp 4

When I call electron.reload the terminal shows 'bound ' ... , it stops there, and nothing reloads. The code calling reload is:

gulp.watch(paths.appHtml, gulp.series('copy:index', 'copy:spa-for-electron', electron.reload));

electron.restart works in place of reload above, but reload is the correct action here.

Connection error (ECONNREFUSED)

I get the following 2 errors when the client tries to connect:

A JavaScript error occurred in the main process

Uncaught Exception:
Error: connect ECONNREFUSED 127.0.0.1:30080
    at Object.exports._errnoException (util.js:1022:11)
    at exports._exceptionWithHostPort (util.js:1045:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
A JavaScript error occurred in the main process

Uncaught Exception:
Error: socket hang up
    at createHangUpError (_http_client.js:253:15)
    at Socket.socketCloseListener (_http_client.js:285:23)
    at emitOne (events.js:101:20)
    at Socket.emit (eventsjs:188:7)
    at TCP._handle.close [as _onclose] (net.js:501:12) 

Operating system: Windows 7
Electron: 1.6.7

This happens if I try to connect in the renderer process too with the exceptions being reported in the console.

Repro project available at https://github.com/leonard-thieu/electron-connect-econnrefused

Related to #23.

restart does not close existing instance

i am on linux x64. the restart method seems to keep the existing instance alive, so i end up having multiple windows on making a change. in gulp i am using watch:

gulp.watch(['./app/main.js'], electron.restart);

i am using node v5.0.0 and electron-prebuilt v0.34.3.

probably something wrong my end, but would appreciate a response. many thanks.

electron.restart blocked on before-quit task

I have set up a project where I use electron-connect in a gulpfile. Whenever I do modifications inside my electron server I call the electron.restart task.

I've added listeners on electron's before-quit, will-quit and quit events to log when they're called. When I quit my app with a SIGKILL (ctrl+c) in my terminal, everything just works as excepted (before-quit -> will-quit -> quit). However when I update a server-side file, only the before-quit event is called and I need to quit the app itself to continue the process and restart the app.

I'm not sure where that comes from..

Need better test scripts to verify commits.

Current test script doesn't verify whether electron app was created successfully or not. Test gets passed even when there is an issue with starting electron app from simple example code.

Gulp serve or electron restart do not maximize window

In the browser process's main.js, i have

const client = require("electron-connect").client;

//snip
mainWindow = new BrowserWindow({width: 400, height: 600});
mainWindow.maximizable();

client.create(mainWindow);

Similar to issue #30, after running "gulp serve" or on electron.restart(), I would expect to see the displayed window to have maximized, but it is not. However, when I run "electron .", the window maximized.

Help configuring with webpack

Hi! Thanks for develop this tool. I'm trying to use this with webpack, and I successfully had setup basic reload. However, I would like some additional task to be handle.
This is my actual file:

/*
 * @author: @michaeljota
 */

const appRoot = require('app-root-path');

const mainThreadConfig = require('./main'); // Resolve the Webpack config file for the main thread.
const rendererThreadConfig = require('./renderer'); // Resolve the Webpack config file for the renderer thread.

const webpackMerge = require('webpack-merge');
const { server, client } = require('electron-connect');

const electron = server.create({ path: appRoot.resolve('dist') }); // Create the server in the output folder

/*
 * Webpack Plugins
 */
const { ProvidePlugin } = require('webpack');
const WebpackOnBuildPlugin = require('on-build-webpack');

module.exports = (env) => {
  let started = false;

  return [
    // The Electron main thread configuration
    webpackMerge(mainThreadConfig(env), {
      plugins: [
        new WebpackOnBuildPlugin(function (stats) {
          if (!started) {
            started = true;
            electron.start();
          } else {
            electron.restart();
          }
        }),
        new ProvidePlugin({
          livesyncClient: client,
        }),
      ],
    }),
    // The Electron renderer thread configuration
    webpackMerge(rendererThreadConfig(env), {
      plugins: [
        new WebpackOnBuildPlugin(function (stats) {
          if (started) {
            electron.reload();
          }
        }),
      ],
    }),
  ];
};

What I want it's to the electron-connect to only reload the renderer thread when the renderer files changes, and the reload the whole application when the main files changes.

It's that posible? Thanks you.

Why not use 127.0.0.1 instead of localhost?

Thanks for building such a timesaving tool.

When I try to add this amazing tool into my project to implement live reload, I got an Error with config by default.

image

There is a DNS lookup problem. I know our local hosts will parse 'localhost' to '127.0.0.1' by default, but if I change my host with some tools (Switch Hosts etc.). The '127.0.0.1 localhost' might be rewrote or deleted which leading to the problem showing above.

So, Why not use 127.0.0.1 instead of localhost to solve this potential problem.

Thanks for your work again.

Fails to electron.reload() when preceded by other gulp tasks

Hi, I'm having an issue reloading successfully my electron app after a scss change. As you can imagine, I need to transform my scss resource into a css file, which implies a gulp task prior reloading the electron app.

In partitioning the issue I noticed that any gulp task prior electron.reload was resulting in a crash. ie: following 'watch' task triggers 'noop' then 'reload:renderer' tasks

gulp.task('watch', function () {
    gulp.watch([
        path.join(conf.paths.src, '/app/**/*.css'),
        path.join(conf.paths.src, '/app/**/*.scss')
    ], function (event) {

        gulp.start('noop')
            .pipe('reload:renderer')
    })
})

gulp.task('noop', function () {
});

gulp.task('reload:renderer', function (done) {
  // Reload renderer process
  electron.reload();
  done();
});

Am I missing something ?

Cannot read property 'object' of undefined

On first start, and whenever a change occurs, I see the following stacktrace. Note that it's electron-connect's socket.on('message') callback that is causing this.

electron-prebuilt: 0.37.2 (though it was also occurring with 0.36.11)
electron-connect: 0.3.7

TypeError: Cannot read property 'object' of undefined
    at ObjectsRegistry.get (/home/mitch/dev/james/node_modules/electron-prebuilt/dist/resources/atom.asar/browser/objects-registry.js:44:28)
    at EventEmitter.<anonymous> (/home/mitch/dev/james/node_modules/electron-prebuilt/dist/resources/atom.asar/browser/rpc-server.js:337:31)
    at emitThree (events.js:97:13)
    at EventEmitter.emit (events.js:175:7)
    at EventEmitter.<anonymous> (/home/mitch/dev/james/node_modules/electron-prebuilt/dist/resources/atom.asar/browser/api/web-contents.js:144:25)
    at emitTwo (events.js:87:13)
    at EventEmitter.emit (events.js:172:7)
    at ObjectsRegistry.get (/home/mitch/dev/james/node_modules/electron-prebuilt/dist/resources/atom.asar/browser/objects-registry.js:44:28)
    at EventEmitter.<anonymous> (/home/mitch/dev/james/node_modules/electron-prebuilt/dist/resources/atom.asar/browser/rpc-server.js:337:31)
    at emitThree (events.js:97:13)
    at EventEmitter.emit (events.js:175:7)
    at EventEmitter.<anonymous> (/home/mitch/dev/james/node_modules/electron-prebuilt/dist/resources/atom.asar/browser/api/web-contents.js:144:25)
    at emitTwo (events.js:87:13)
    at EventEmitter.emit (events.js:172:7)
    at metaToValue (/home/mitch/dev/james/node_modules/electron-prebuilt/dist/resources/atom.asar/renderer/api/remote.js:170:13)
    at BrowserWindow.descriptor.get [as webContents] (/home/mitch/dev/james/node_modules/electron-prebuilt/dist/resources/atom.asar/renderer/api/remote.js:118:16)
    at EventEmitter.<anonymous> (/home/mitch/dev/james/node_modules/electron-connect/lib/client.js:108:21)
    at emitOne (events.js:77:13)
    at EventEmitter.emit (events.js:169:7)
    at EventEmitter.<anonymous> (/home/mitch/dev/james/node_modules/electron-connect/lib/client.js:64:16)
    at emitTwo (events.js:87:13)
    at WebSocket.emit (events.js:172:7)
    at Receiver.ontext (/home/mitch/dev/james/node_modules/ws/lib/WebSocket.js:816:10)
    at /home/mitch/dev/james/node_modules/ws/lib/Receiver.js:477:18

ECONNREFUSED

[24840:0112/222627:INFO:CONSOLE(141)] "Uncaught Error: connect ECONNREFUSED 127.0.0.1:30080", source: events.js (141)
[24840:0112/222627:INFO:CONSOLE(141)] "Uncaught Error: socket hang up", source: events.js (141)

`Bad argument` when trying to start server.

Using node.js version v4.1.1, I get the following error when trying to start the server:

internal/child_process.js:274
  var err = this._handle.spawn(options);
                         ^

TypeError: Bad argument
    at TypeError (native)
    at ChildProcess.spawn (internal/child_process.js:274:26)
    at Object.exports.spawn (child_process.js:339:9)
    at EventEmitter.ProcessManager.spawn (/Users/usandfriends/Documents/GitHub/electron-test/node_modules/electron-connect/lib/server.js:28:28)
    at EventEmitter.<anonymous> (/Users/usandfriends/Documents/GitHub/electron-test/node_modules/electron-connect/lib/server.js:47:10)
    at Server.g (events.js:260:16)
    at emitNone (events.js:72:20)
    at Server.emit (events.js:166:7)
    at emitListeningNT (net.js:1257:10)
    at doNTCallback1 (node.js:418:9)

reload() throws "Error: Object has been destroyed", with client.create() called from browser process.

Steps to recreate the issue

  1. Using code from issue #45
  2. run gulp serve
  3. close one of the windows.
  4. Now, touch win1.html or touch win2.html to trigger electron-connect's server reload()

Actual Result

Error: Object has been destroyed is seen on the console.

Error: Object has been destroyed
    at Error (native)
    at EventEmitter.<anonymous> (/Users/ssettipalli/Downloads/_personal_work/opensource/electron-connect/lib/client.js:114:21)
    at emitOne (events.js:101:20)
    at EventEmitter.emit (events.js:188:7)
    at EventEmitter.<anonymous> (/Users/ssettipalli/Downloads/_personal_work/opensource/electron-connect/lib/client.js:64:16)
    at emitTwo (events.js:106:13)
    at WebSocket.emit (events.js:191:7)
    at Receiver.ontext (/Users/ssettipalli/Downloads/_personal_work/opensource/electron-connect/node_modules/ws/lib/WebSocket.js:841:10)
    at /Users/ssettipalli/Downloads/_personal_work/opensource/electron-connect/node_modules/ws/lib/Receiver.js:536:18
    at /Users/ssettipalli/Downloads/_personal_work/opensource/electron-connect/node_modules/ws/lib/Receiver.js:368:7

Expected Result

Throws no error.

Handling popup exceptions

I have recently filed an issue, within the realm of the Electron project โ€” a case which refers to a condition where Electron raises an exception, alongside with a JavaScript window popup. Such window, specifically in Linux, becomes separated from the main app process; therefore, a CTRL+C issued command, for example, will properly kill the main app but not the separated process associated with the exception (An Electron spawned process is kept alive in Linux.)

The issue is ( screenshots and testcase included )
electron/electron#7530

Within that project, I yet believe it's an interesting case to look at, because IMHO Electron should not start creating popups by default. Plus, in Mac, at least the main process kills the spawned JS error window.

Nevertheless, I believe that such condition is even more critical for a project like electron-connect, as we assume that such project is positioned as an effective means to launch/start/restar/stop operations. I wonder if such control could be integrated in electron-connect side as opposite to asking the developer to create an exception handler within their Browser side app.

electron.reload doesn't work

Encountered with Node v7.0.0, Electron v1.4.12 & npm v3.10.8. electron.reload doesn't seem to work when I modify my index.html while electron.restart works perfectly when I modify app.js.

My gulpfile:

const gulp     = require('gulp');
const electron = require('electron-connect').server.create();

gulp.task('serve', function() {
  electron.start();
  gulp.watch('app.js', electron.restart);
  gulp.watch(['index.js','index.html'], electron.reload);
});

gulp.task('default', ['serve']);

Will you come up with a fix, or is there a way to overcome the problem? Thanks.

Edit: Nevermind, I forgot to register my client tho...

stopping the process on window close

thank you for this great project. i was just wondering if it is possible to stop the process on closing the app window by using an event handler or similar? thanks

browserWindow 'closed' event handler not getting invoked.

I have the following sample code along with other .html files for main window and child window. You can find the entire code at the repo url - https://bitbucket.org/ssreekanth/sample-electron-connect.git

var app = require('app'),
      BrowserWindow = require('browser-window'),
      ipc = require('ipc');

  var mainWindow = null;
  var childWindow = null;

  app.on('window-all-closed', function() {
      if (process.platform != 'darwin') {
          app.quit();
      }
  });

  app.on('ready', function() {
      mainWindow = new BrowserWindow({
          width: 480,
          height: 640,
          resizable: false
      });

      mainWindow.loadUrl('file://' + __dirname + '/main.html');

      mainWindow.on('closed', function() {
          mainWindow = null;
      });

      ipc.on('child:open', function(event) {
          console.log('main.js :: ipc msg child:open received');
          openChildWindow();
      });

      openChildWindow = function() {
          childWindow = new BrowserWindow({
              width: 1080,
              height: 640,
          });

          childWindow.loadUrl('file://' + __dirname + '/child.html');

          childWindow.on('closed', function() {
              console.log('child window closed');
              childWindow = null;
          });
      };
  });

When not integrated with 'electron-connect', all works fine. childWindow.on('closed', function() {}) gets invoked and I could see the 'child window closed' message getting printed on the console.

However, when I enable electron-connect, I don't see this handler getting invoked. Looks like electron-connect is handling the 'close' event, but the app doesn't see the same event.

What could be wrong? How to fix this?

Work with babel

I cannot get this to work with babel, getting import token import problem.

electron.reload doesn't work

The following code inside my gulpfile.js works when using electron.restart, but does nothing when using electron.reload.

var
    gulp = require('gulp'),
    electron = require('electron-connect').server.create()
;

gulp.task('serve', function () {
    electron.start();
    gulp.watch(['app/**/*'], electron.reload);
});

Is this a bug or am I missing something?

(There was a new Electron release two days ago. Just in case...)

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.