Showing posts with label electron. Show all posts
Showing posts with label electron. Show all posts

Thursday, September 27, 2018

Error while loading electron-tabs module & unable to create tabs in electron

Leave a Comment

I have installed electron-modules package for implementing tabs in electron as shown below

package.json

{   "name": "Backoffice",   "version": "1.0.0",   "description": "BackOffice application",   "main": "main.js",   "scripts": {     "start": "electron ."   },   "author": "Karthik",   "license": "ISC",   "devDependencies": {     "electron": "^2.0.8",     "electron-tabs": "^0.9.4"   } } 

main.js

const electron = require("electron"); const app = electron.app; const BrowserWindow = electron.BrowserWindow; const Menu = electron.Menu; const path = require("path"); const url = require("url"); const TabGroup = require("electron-tabs");  let win; const tabGroup = new TabGroup();  function createWindow() {     win = new BrowserWindow();     win.loadURL(url.format({         pathname:path.join(__dirname,'index.html'),         protocol:'file',         slashes:true     }));      win.on('closed',()=>{         win = null;     }) }  app.on('ready', function(){     createWindow();     const template = [         {             label : 'Backoffice',             submenu: [                 {                    label : 'Account Management',                    click : function () {                        let tab = tabGroup.addTab({                        title: "Electron",                        src: "http://electron.atom.io",                        visible: true                     });                     }                 },                 {                     label : 'HR Management',                     click : function () {                         console.log("CLICK HM menu");                     }                     },              ]          } ]     const menu = Menu.buildFromTemplate(template);     Menu.setApplicationMenu(menu); }); 

index.html

<!DOCTYPE html> <html lang="en">     <head>         <title>BackOffice</title>         <link rel="stylesheet" href="styles.css">         <link rel="stylesheet" href="node_modules/electron-tabs/electron-tabs.css">     </head>     <body>         <h1>BackOffice</h1>         <div class="etabs-tabgroup">             <div class="etabs-tabs"></div>             <div class="etabs-buttons"></div>         </div>         <div class="etabs-views"></div>     </body> </html> 

I am getting the following error when I run npm start

App threw an error during loadReferenceError: document is not defined at Object.<anonymous> (C:\workspace\nodejs_workspace\electron\menu-demo\node_modules\electron-tabs\index.js:3:1)     at Object.<anonymous> (C:\workspace\nodejs_workspace\electron\menu-demo\node_modules\electron-tabs\index.js:421:3)     at Module._compile (module.js:642:30)     at Object.Module._extensions..js (module.js:653:10)     at Module.load (module.js:561:32)     at tryModuleLoad (module.js:504:12)     at Function.Module._load (module.js:496:3)     at Module.require (module.js:586:17)     at require (internal/module.js:11:18)     at Object.<anonymous> (C:\DEV_2018\nodejs_workspace\electron\menu-demo\main.js:11:18) 
  • Why am I not able to load electron-modules package.

  • What is causing this error? How to create a new tab on click on application menu in electron?

3 Answers

Answers 1

As @coolreader18 explained in details, you have to use electron-tabs in Renderer process

This means you have to notify the html from main.js when you click a menu item. MenuItem's click provides you the caller BrowserWindow so you can send message to it.

main.js

 ...  {    label: 'Account Management',    click: function (menuItem, browserWindow, event) {      browserWindow.webContents.send('add-tab', {        title: 'Electron',        src: 'http://electron.atom.io',        visible: true      })    }  },  ... 

index.html

<body>   ...   <script>     const { ipcRenderer } = require('electron')     const TabGroup = require('electron-tabs')     const tabGroup = new TabGroup()      ipcRenderer.on('add-tab', (event, arg) => {       tabGroup.addTab(arg)     })   </script> </body> 

Answers 2

In the documentation for electron-tabs, it mentions to call it from the renderer process, yet you're doing it in the main process. The main process is where you control the electron apis from, e.g. opening windows like you are in main.js. Each browser window creates a new renderer process, which can communicate with the main process or manage its own document and Web APIS.

The error you're getting there, document is not defined, is because the main process does not have access to the DOM because you can open multiple browsers from the same main process; it wouldn't know which to use. So what you need to do is put a script in the renderer process. Create a renderer.js, and put the electron-tabs code (const TabGroup = require("electron-tabs");) there. Then, in your index.html, put <script src="renderer.js"></script>, and it should work.

Answers 3

Could be because you are calling

const tabGroup = new TabGroup(); 

before the page has finished loading.

Try splitting it up into

let tabGroup; 

and inside of createWindow():

tabGroup = new TabGroup(); 

Edit: You have to change const to let or var then, sorry

Read More

Tuesday, August 21, 2018

How to transfer files to a usb mount with electron

Leave a Comment

In an electron app I'm trying to transfer some files in an attached usb device.

I used usb-detection module to detect a new usb but it doesn't give any details about the mount path so how can I transfer files?

(Preferably cross platform solution)

1 Answers

Answers 1

First you can use os.platform() to define the OS with file system. Then nodejs exec to spawn a process to be able to execute bash code to actually get the list of drives. Then simply return those values and use in the code with fs. Checkout in the example here.

Read More

Saturday, July 21, 2018

Electron Manipulate/Intercept WebView Requests and Responses

Leave a Comment

I want to create an Electron app that will use webview to display 3rd party content.

I would like to be able to intercept all requests and responses from this webview. Sometimes I would like to manipulate this content, other times I would like to log it, and other times I’d like to do nothing.

As one example for the responses, maybe a web server will respond with TypeScript code, maybe I want to take that response, and compile it to standard JavaScript.

I have looked into this page but it looks like it is only possible to cancel requests, and manipulate the headers. The WebRequest API doesn't look to fit the needs of my use case since it only allows very minor manipulations of requests and responses.

I have also considered setting up some time of web server that can act as a proxy, but I have concerns about that. I want to maintain user privacy, and I want to ensure that to the web servers that host the 3rd party content it looks like the request is coming from a browser like environment (ex. Electron webview) instead of a server. I know I can manipulate requests with the headers I send and such, but this whole solution is getting to be a lot more complicated, then I would like, but might be the only option.

Any better ways to achieve this, and have more control over the Electron webview?

1 Answers

Answers 1

I think you should look into The Protocol API. it works as a proxy internally. say you wanna the user open http://www.google.com and see content like you've been conned!.

const { protocol } = require("electron");    const content = new Buffer("you've been conned!");    protocol.interceptBufferProtocol("http", (request, result) => {    if (request.url === "http://www.google.com")      return result(content);    ... // fetch other http protocol content and return to the electron  });

there's lots of work to do, comparing to the WebRequest API. but it's much simpler than a independent local proxy.

Read More

Friday, May 11, 2018

how to get a Network Panel show up when debugging Electron/Node applications

Leave a Comment

I am building an electron application and I am using libraries (request/axios) for making requests. One thing I didn't expect is that making these requests on Node won't display a Network Panel when running in chrome debug mode. Is there a simple way to tell debug mode to turn on a network panel for tuning into https requests(I assume these libraries all use https)?


currently on my server side electron app i only see the following enter image description here

1 Answers

Answers 1

Solution 1 - create your own

you can wrap your axios functions and send an event to your renderer process

main electron process

const electron = require('electron');  const {   app,   BrowserWindow,   ipcMain } = electron;  const _axios = require('request-promise');  const axios = {   get: (url, params) => _axios.get(url, params).then(sendData),   post: (url, params) => _axios.post(url, params).then(sendData),   delete: (url, params) => _axios.delete(url, params).then(sendData),   put: (url, params) => _axios.put(url, params).then(sendData)   // ... };  function sendData() {   return (data) => {     mainWindow.webContents.send('network', data);     return data;   }; } 

renderer process (index.html):

<!DOCTYPE html> <html>  <head>   <meta charset="UTF-8">   <title>Hello World!</title>    <link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css"          rel="stylesheet">   <style>     .kb-debug-widget {       position: fixed;       bottom: 0;       height: 200px;       overflow-x: hidden;       overflow-y: auto;       background: grey;       left: 0;       right: 0;       font-size: 10px;     }   </style> </head>  <body>   <div class="kb-debug-widget">     <table class="table is-bordered is-striped is-narrow is-hoverable is-fullwidth"            id="network">       <tr>         <th>Name</th>         <th>Method</th>         <th>Status</th>         <th>Type</th>         <th>Body</th>       </tr>     </table>   </div>   <script>     require('./renderer.js');     var {       ipcRenderer,       remote     } = require('electron');      ipcRenderer.on('network', (event, response) => {       const networkElement = document.getElementById('network');        // print whatever you want here!       networkElement.innerHTML +=         `       <tr>         <td>${response.request.href}</td>         <td>${response.request.method}</td>         <td>${response.statusCode}</td>         <td>${response.headers['content-type']}</td>         <td>${response. data}</td>       </tr>       `;        // you can also print the network requests to the console with a decent UI by using console.table:       console.table({         name: response.request.href,         method: response.request.method,         status: response.statusCode,         type: response.headers['content-type'],         body: response. data,       });     });   </script> </body>  </html> 

This will create a widget on the bottom of your view.

it's even easier with request:

const _request = require('request-promise'); const _axios = require('request-promise');  // this should cover all sub-methods const request = (params, callback) => {   return _request(params, callback)   .on('response', (response) => {     mainWindow.webContents.send('network', response);     return response;   }); }; 

Since both axios & request return similar objects, you can use the same function on the renderer side.

code in action

enter image description here

Here's a GitHub repository with the code implemented

Solution 1: Alt - write network requests to renderer's console

I also added an option to print the requests to the dev tools console, with console.table. Here's how it looks: enter image description here You can leave only this method if you don't want a widget inside your HTML.

Solution 2 - Run electron with the --inspect flag

You can also just run electron with the inspect flag, which allows you to debug your server code and has its own network tab with the "server-side" HTTP requests.

In order to see it, run your electron application like so:

electron --inspect=<port> your/app 

if you want to immediatly break on the first line, run the same command but replace --inspect with --inspect-brk.

After running the command, open any web-browser and go to chrome://inspect and selecting to inspect the launched Electron app present there. enter image description here

hope this helped. if you have any questions, you can ask me in the comments

Read More

Wednesday, May 2, 2018

Is it possible to show an alternative menu when holding “Alt” on an opened context menu in Electron?

Leave a Comment

On macOS, when right-clicking on a file, then holding Alt, it does show more advanced options. Is it possible to reproduce it using Electron? Thank you!

1 Answers

Answers 1

The answer is yes. Although a built-in feature is not provided it is possible to customize your context menu & options as described here:

https://github.com/sindresorhus/electron-context-menu

https://github.com/parro-it/electron-contextmenu-middleware

Furthermore it's possible to customize shortcuts for your modifications this way:

https://electronjs.org/docs/tutorial/keyboard-shortcuts

Read More

Friday, April 27, 2018

System freezes when parent and child connectivity

Leave a Comment

I have used Pouchdb with Electron, connected two system through local LAN and using the single database which is a parent and another child system will be using the same pouchdb database.

used express-pouch to make child system to connect parent pouchdb.

There is background sync will be running in parent system from couchDB to pouchDB.

The connection is working as expected, Problem will be after some time of connection system freezes in both parent and child. checked task manager disk 100%, memory 100%.

Both System - windows 10 pro - Ram - 4GB

1 Answers

Answers 1

Try to increase memory allocated for your script with the option --max_old_space_size=<size>.

Try too to monitor number of emitter you have with method emitter.getMaxListeners() and emitter.listenerCount(eventName), and increase the number with emitter.setMaxListener(n)

Read More

Thursday, March 15, 2018

How to create offline web app with JavaScript that can read local file and parse?

Leave a Comment

I'm trying to create an app with a browser interface that allows users to input a text file and then parse it for certain phrases. I have all the logic/regex I need to do the parsing, I just don't know how to implement it into a webpage interface.

What I currently have uses node.js and only works when I run the command with node (not in the browser) and hardcode the path to the file on my local system.

const fs = require("fs"); const text = fs.readFileSync("C:\\Users\\bob\\Desktop\\test\\sample.txt", "utf-8");  const textByLine = text.split("\n");   //rest of script logic below 

I've been researching things like require.js and browserify which from what I understand, allow you to use node.js on client side, but I'm not sure if this is what I need.

I sort of want to make an electron app, but I'd rather build it out as a webapp first.

Is this the best way to go about accomplishing what I'm trying to do?

4 Answers

Answers 1

The easiest solution for this would likely be a simple webpage using some of the browser-based File APIs, and would not require using NodeJS. @Quentin's Another duplicate comment above links to a good example of this. With this style the user has to provide the file to be input though and your script cannot just go willy-nilly looking for it or accessing the user's disk as it pleases. While it is possible to use some of the NodeJS modules or user-made modules in the browser the support is limited. There are no browser-based replacements for many low-level parts of NodeJS, and because of this some modules do not/cannot support the browser directly, but many (where possible) have at least one alternative.

Second would be a NodeJS CLI app. As it would only run in the terminal it would not be difficult to setup using one of the many libraries to help make CLI apps for NodeJS such as commander.js or node-js-libs/cli.

Finally, a full-blown Electron app would be the most complex. It's essentially the best-of browser and NodeJS worlds as it's GUI capable and supports [almost?] all of the standard NodeJS libraries, but of course it adds another layer of complexity because Electron has it's own API too. A big bonus though is that it's also pretty easily cross-platform capable and you don't need to write a bunch of cross-platform browser supporting code as it only uses Chromium (Chrome) underneath.

Edit: Clarifying based on ghybs's excellent point in the comments.

Answers 2

I would suggest you setup a simple Nodejs server application with express.js framework.

Then you use multer or node library to upload your text file and then through your logic your said you have you can create a controller to handle the business logic for parsing the phrase within the text you have uploaded and read . You can send request to the node and get response after processing the phrases you can send response back to the client/browser interface. Hopefully , this idea might be what you are looking for.
Express setup
Multer documentation
express file uplopader documentation.
Maybe this will help you setup a node and express app. If you need it Node&express setup

Answers 3

The browser (regular javascript) doesn't have access to users system files because it is a security risk, what you would want to do is have a form for saving a file to LocalStorage which is then read by your javascript file. That would be if you want a pure javascript implementation.

If you're using NodeJs you could have access to the file system using the package (fs) you were using above to save and read the file. With this, you'd want the user to submit the file via a html/javascript webform that sends the file to a backend endpoint which is then saved to the projects directory using fs module. Then, from the node script would read/parse that file, and serve the desired results back to the user via another endpoint that the user requests.

Answers 4

use nodejs is best way to create local application, sometime you can use https://electronjs.org/ to build native app, Are you using Atom ? It can build by electron :D

Read More

Saturday, December 16, 2017

PouchDB in Electron, set data storage location

Leave a Comment

I am writing an Electron application that will need to store a large amount of data on the client. I want to use PouchDB but I need to have control over the location where the database is held on the user's PC. I can't find anything in the docs about it.

1 Answers

Answers 1

Setting the location of the database is very simple.

db = new PouchDB(dbFilePath); 

You can set the dbFilePath to the path that you want. For example, I want to set the path to where the Electron application runs. So I do the following.

const appDataDirectory = app.getPath('appData'); let dbFilePath = appDataDirectory + '/data/'; if (process.env.NODE_ENV === 'development') {   dbFilePath = './data/'; } log.debug('NODE_ENV:%s, dbFilePath:%s', process.env.NODE_ENV, dbFilePath); let db = new PouchDB(dbFilePath); 
Read More

Monday, September 11, 2017

How to successfully use express routing in electron project?

Leave a Comment

I am using ExpressJS in my Electron project. The routing with Express doesn't work as expected.

Here is how I created the routing (in the main process):

const express = require('express')  const app2 = express()  app2.get('/requests/:_id', (req, res, next) =>   {   console.log('Dynamic Link WORKS!!');   hosSchemaModel.findOne({ _id: req.params._id }, function(err, request){     res.json(request)     // res.sendFile(path.join(__dirname+'../homePage.html'))   }); }); 

And in the front-end I have the following:

<a href="/requests/{{this._doc._id}}">{{this._doc.status}}</a> 

When I click on {{this._doc.status}} the it takes me to empty white screen with nothing printed in the console.

Can I have some guidance on how to implement ExpressJS routing in Electron?

2 Answers

Answers 1

Just a shot in the dark but you won't be able to connect without a port. Try adding this to the end of your server file. 'app2.port(9000)` then try hitting the same URL but with a port.

Answers 2

Electron has basically two process main and rendered process, when you are printing console.log, it is basically printing in your main process's console. You have to pass data to renderer process to show in console of your web page.

UPDATE - 2

Make express sever to listen to some port, then from frontend hit the url having that port also.

Main.js

app2.get('/requests/1234', (req, res, next) =>   {   console.log('Dynamic Link WORKS!!');   hosSchemaModel.findOne({ _id: req.params._id }, function(err, request){     res.json(request);     // res.sendFile(path.join(__dirname+'../homePage.html'))   }); });  app2.listen(5000, function () {   console.log('Example app listening on port 3000!'); }); 

frontend

<a href="localhost:5000/requests/1234">{{this._doc.status}}</a> 

After this it is working at my end.

If you want to run the express server in cluster mode, you should fork the process and try running the express server in new process.

Read More

Monday, June 12, 2017

How to manage configuration for Webpack/Electron app?

Leave a Comment

I am using Webpack 2 and Electron to build nodejs application on Mac.

In my project in the root I have directory 'data' where I store configuration in a json like data/configurations/files.json (in practices there are different files with dynamic names)

After webpackaing though when I call: fs.readdirSync(remote.app.getAppPath()); to get files in the root I get only these packed: [ "default_app.js", "icon.png", "index.html", "main.js", "package.json", "renderer.js" ]

path.join(remote.app.getAppPath(), 'data/tests/groups.json'); called with FS ReadSync leads to an issue Error: ENOENT, data/tests/groups.json not found in /Users/myuser/myproject/node_modules/electron/dist/Electron.‌​app/Contents/Resourc‌​es/default_app.asar. So it seems that the whole data folder is not picked up by webpacker.

Webpack config is using json-loader and I did not find any documentation mentioning anything special about including specific files or jsons. Or do I have to reference json files in my code differently as they might be packed under main.js.

What is the best practice for Electron/Webpack for managing JSON config files? Am I doing something wrong when webpacking the project?

My project is based of https://github.com/SimulatedGREG/electron-vue using webpack/electron/vue

3 Answers

Answers 1

The Webpack Misconception

One thing to understand upfront is that webpack does not bundle files required through fs or other modules that ask for a path to a file. These type of assets are commonly labeled as Static Assets, as they are not bundled in any way. webpack will only bundle files that are required or imported (ES6). Furthermore, depending on your webpack configuration, your project root may not always match what is output within your production builds.

Based on the electron-vue documentation's Project Structure/File Tree, you will find that only webpack bundles and the static/ directory are made available in production builds. electron-vue also has a handy __static global variable that can provide a path to that static/ folder within both development and production. You can use this variable similar to how one would with __dirname and path.join to access your JSON files, or really any files.

A Solution to Static Assets

It seems the current version of the electron-vue boilerplate already has this solved for you, but I'm going to describe how this is setup with webpack as it can apply to not only JSON files and how it can also apply for any webpack + electron setup. The following solution assumes your webpack build outputs to a separate folder, which we'll use dist/ in this case, assumes your webpack configuration is located in your project's root directory, and assumes process.env.NODE_ENV is set to development during development.

The static/ directory

During development we need a place to store our static assets, so let's place them in a directory called static/. Here we can put files, such as JSONs, that we know we will need to read with fs or some other module that requires a full path to the file.

Now we need to make that static/ assets directory available in production builds.

But webpack isn't handling this folder at all, what can we do?

Let's use the simple copy-webpack-plugin. Within our webpack configuration file we can add this plugin when building for production and configure it to copy the static/ folder into our dist/ folder.

new CopyWebpackPlugin([     {       from: path.join(__dirname, '/static'),       to: path.join(__dirname, '/dist/static'),       ignore: ['.*']     } ]) 

Okay so the assets are in production, but how do I get a path to this folder in both development and production?

Creating a global __static variable

What's the point of making this __static variable?

  1. Using __dirname is not reliable in webpack + electron setups. During development __dirname could be in reference to a directory that exists in your src/ files. In production, since webpack bundles our src/ files into one script, that path you formed to get to static/ doesn't exist anymore. Furthermore, those files you put inside src/ that were not required or imported never make it to your production build.

  2. When handling the project structure differences from development and production, trying to get a path to static/ will be highly annoying during development having to always check your process.env.NODE_ENV.

So let's simplify this by creating one source of truth.

Using the webpack.DefinePlugin we can set our __static variable only in development to yield a path that points to <projectRoot>/static/. Depending if you have multiple webpack configurations, you can apply this for both a main and renderer process configuration.

new webpack.DefinePlugin({     '__static': `"${path.join(__dirname, '/static').replace(/\\/g, '\\\\')}"` }) 

In production, we need to set the __static variable manually in our code. Here's what we can do...

index.html (renderer process)

<!-- Set `__static` path to static files in production --> <script>     if (process.env.NODE_ENV !== 'development') window.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\') </script> <!-- import webpack bundle --> 

main.js (main process)

// Set `__static` path to static files in production if (process.env.NODE_ENV !== 'development') {     global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\') }  // rest of application code below 

Now start using your __static variable

Let's say we have a simple JSON file we need to read with fs, here's what we can accomplish now...

static/someFile.json

{"foo":"bar"} 

someScript.js (renderer or main process)

import fs from 'fs' import path from 'path'  const someFile = fs.readFileSync(path.join(__static, '/someFile.json'), 'utf8')  console.log(JSON.parse(someFile)) // => { foo: bar } 

Conclusion

webpack was made to bundle assets together that are required or imported into one nice bundle. Assets referenced with fs or other modules that need a file path are considered Static Assets, and webpack does not directly handle these. Using copy-webpack-plugin and webpack.DefinePlugin we can setup a reliable __static variable that yields a path to our static/ assets directory in both development and production.

To end, I personally haven't seen any other webpack + electron boilerplates handle this situation as it isn't a very common situation, but I think we can all agree that having one source of truth to a static assets directory is a wonderful approach to alleviate developer fatigue.

Answers 2

I think the confusion, (if there is any), might come from the fact that webpack not only "packs", embeds, things, code, etc... but also process content with its plugins.

html plugin being a good example, as it simply generates an html file at build-time.

And how this relates to the config file issue?, well depending on how you are "requiring" the "config" file, what plug-in you are using to process that content.

You could be embedding it, or simply loading it as text, from file system or http, or else...

In the case of a config file, that I guess you want it to be parsed at runtime,
otherwise it's just fancy hardcoding values that perhaps you could be better simply typing it in your source code as simple objects.

And again in that case I think webpack adds little to nothing to the runtime needs, as there is nothing to pre-pack to read at later use,

so I would possibly instead or "require"it, i'll read it from the file system, with something like :

// read it parse it relative to appPath/cwd,  const config = JSON.parse(     fs.readfileSync(          path.join( app.getAppPath(), "config.json" ),         "utf-8"     )) //note: look fs-extra, it does all that minus the app.path plus async 

and electron will read it from the file system , or if using Electron.require will read it from asar|fileSystem (in that order if I remember correctly, I could be wrong),

Answers 3

Webpack design philosophy is focused around very simple yet powerful concept:

Transform and bundle everything that is actually used by your app.

To achieve that webpack introduces a powerful concept of dependency graph, which is able to manage virtually any kind of dependencies (not only *.js modules) by the means of so-called loaders.

The purpose of a loader is to transform your dependency in a way that makes statement import smth from 'your_dependency' meaningful. For instance, json-loader calls JSON.parse(...) during loading of *.json file and returns configuration object. Therefore, in order to take advantage of webpack dependency resolution system for managing JSONs, start from installing json-loader:

$ npm install --save-dev json-loader 

Then modify your webpack.config.js in the following way:

module.exports = {   ...   module: {     rules: [       {test: /\.json$/, use: 'json-loader'}     ]   }   ... }; 

At this point webpack should be able to resolve your JSON dependencies by their absolute paths, so the following should work (I assume here that you have a subdirectory config of your root context dir, containing file sample.json):

import sampleCfg from './config/sample.json'; 

But importing physical paths doesn't lead to elegant, robust and maintainable code (think of testability, for example), so it is considered a good practice to add aliases to your webpack.config.js for abstracting away your physical .config/ folder from your import statements

module.exports = {   ...   resolve: {     alias: {       cfg: './config'     }   }   ... } 

Then you'll be able to import your JSON config like that:

import sampleCfg from 'cfg/sample.json' 

Finally, if you use SimulatedGREG/electron-vue Electron project template (as you mentioned in your post), then you have three webpack configuration files:

  • .electron-vue/webpack.web.config.js - use this config file if you use this template just for ordinary web development (i.e. not for building native Electron projects);

  • .electron-vue/webpack.main.config.js - use this file to configure webpack module that will run inside Electron's main process;

  • .electron-vue/webpack.renderer.config.js - use this file for Electron's renderer process.

You can find more information on main and renderer processes in the official Electron documentation.

Read More

Saturday, April 22, 2017

What's the proper way to handle forms in Electron?

Leave a Comment

The form html and submit event is part of the "renderer". The submitted data should be available in the main process. What's the proper way to submit the form and make that data accessible in main.js ?

Should I simply use the "remote" module to pass the data to a function from main.js or is there a better approach?

2 Answers

Answers 1

We use a service (Angular) to process form data in a window. Then notify the remote, if needed.


From your renderer you can send data to the ipc, then in you main.js you catch this event and the passed form data:

// renderer.js let ipcRenderer = require('electron').ipcRenderer; ipcRenderer.send('submitForm', formData);  // main.js ipcMain.on('submitForm', function(event, data) {    // Access form data here }); 

You can also send messages back to the renderer from the main.js. Either sync:

// main.js ipcMain.on('submitForm', function(event, data) {    // Access form data here    event.returnValue = {"any": "value"}; }); 

Or async:

// main.js ipcMain.on('submitForm', function(event, data) {    // Access form data here    event.sender.send('formSubmissionResults', results); });  // renderer.js ipcRenderer.on('formSubmissionResults', function(event, args) {    let results = args.body; }); 

Answers 2

There are several variations on how to do this, but all are via IPC. 

IPC (inter process communication) is the only way to get data from the render process to the main process, and is event driven. The way this works is that you can use custom defined events which the process listens for and returns something when that event happens.

The example stated by @Adam Eri is a variation on the ipcMain example found in the documentation, but this method is not one size fits all.

The reason for saying that is the matter can quickly become complicated if you are trying to send events via the menu (which typically runs on the main process), or via components through a front end framework like Vue or Angular.

I will give a few examples:

Using Remote with WebContents

To your point, yes you can use electron remote, but for the purposes of forms it is not the recommended approach. Based on the documentation, the point of remote is to 

Use main process modules from the renderer process

tl:dr -This process can cause deadlocks due to its synchronous nature, can cause event object leaks (due to garbage collection), and leads to unexpected results with callbacks.

Further explanation can be had from the documentation but ultimately this is set for using items like dialog and menu in the render process.

index.js (main process)

const { app, BrowserWindow, ipcMain } = require('electron'); const path = require ('path'); const fs = require('fs'); const os = require('os');  let window;  function createWindow(){     window = new BrowserWindow({         show: false     });      window.loadURL(`file://${__dirname}/index.html`);     window.once('ready-to-show', function (){         window.show();     });      window.webContents.openDevTools();      let contents = window.webContents;      window.on('closed', function() {         window = null;     }); }  exports.handleForm = function handleForm(targetWindow, firstname) {     console.log("this is the firstname from the form ->", firstname)     targetWindow.webContents.send('form-received', "we got it"); };  app.on('ready', function(){     createWindow(); }); 

index.html

<!DOCTYPE html> <html>     <head>         <meta charset="UTF-8">         <title>Electron App</title>     </head>      <body>          <form action="#" id="ipcForm2">             First name:<br>             <input type="text" name="firstname" id="firstname" value="John">             <br>             Last name:<br>             <input type="text" name="lastname" id="lastname" value="Smith">             <br><br>             <input id="submit" type="submit" value="submit">         </form>          <p id="response"></p>          <script src='renderFile.js'></script>     </body> </html> 

renderFile.js (Render Process)

const { remote, ipcRenderer } = require('electron'); const { handleForm} = remote.require('./index'); const currentWindow = remote.getCurrentWindow();  const submitFormButton = document.querySelector("#ipcForm2"); const responseParagraph = document.getElementById('response')  submitFormButton.addEventListener("submit", function(event){         event.preventDefault();   // stop the form from submitting         let firstname = document.getElementById("firstname").value;         handleForm(currentWindow, firstname) });  ipcRenderer.on('form-received', function(event, args){     responseParagraph.innerHTML = args     /*         you could choose to submit the form here after the main process completes         and use this as a processing step     */ }); 

Traditional IPC

index.js (Main Process)

const { app, BrowserWindow, ipcMain } = require('electron'); const path = require ('path'); const fs = require('fs'); const os = require('os');  let window;  function createWindow(){     window = new BrowserWindow({         show: false     });      window.loadURL(`file://${__dirname}/index.html`);     window.once('ready-to-show', function (){         window.show();     });      window.webContents.openDevTools();      let contents = window.webContents;      window.on('closed', function() {         window = null;     }); }  ipcMain.on('form-submission', function (event, firstname) {     console.log("this is the firstname from the form ->", firstname) });  app.on('ready', function(){     createWindow(); }); 

index.html

<!DOCTYPE html> <html>     <head>         <meta charset="UTF-8">         <title>Electron App</title>     </head>      <body>          <form name="ipcForm" onSubmit="JavaScript:sendForm(event)">             First name:<br>             <input type="text" name="firstname" id="firstname" value="John">             <br>             Last name:<br>             <input type="text" name="lastname" id="lastname" value="Smith">             <br><br>             <input type="submit" value="Submit">         </form>          <script src='renderFile.js'></script>     </body> </html> 

renderFile.js (Render Process)

const ipcRenderer = require('electron').ipcRenderer;  function sendForm(event) {     event.preventDefault() // stop the form from submitting     let firstname = document.getElementById("firstname").value;     ipcRenderer.send('form-submission', firstname) } 

Using WebContents

A possible third option is webContents.executeJavascript to access the renderer process from the main process. This explanation from the remote documentation section.

Summary

As you can see, there are a few options on how to handle forms with Electron. So long as you use IPC, you should be fine; its just how you use it that can get you into trouble. I have shown plain javascript options for handling forms, but there are countless ways to do so. When you bring a front end framework into the mix, it gets even more interesting.

I personally use the traditional IPC approach when I can.

Hope that clears things up for you!

Read More

Thursday, January 19, 2017

Info.plist indicates an iOS app, but submitting .pkg

Leave a Comment

I'm getting an error trying to use Application Loader to upload a packaged electron app.

I use electron-packager to package the app with the mas (Mac App Store) platform. I then zipped up the output directory. When I try I to select this .zip file with Application Loader, it gives me this error.

0 Answers

Read More

Sunday, May 8, 2016

How to retrieve an image sent from a desktop app to a Rails API

Leave a Comment

I'm building a desktop app using Electron, which is basically JavaScript.

In it, I'm sending an image to my Rails API like this:

var myHeaders = new Headers(); myHeaders.append('Authorization', 'Token token=redacted'); myHeaders.append('Content-Type', 'application/json'); myHeaders.append('Accept', 'application/json');  ...  var formData = new FormData(); formData.append("img", base64EncodedImage); var myPost = {method: 'POST', headers: myHeaders, body: formData} fetch("url", myPost) 

(simplified)

In my Rails console, I see:

{"REMOTE_ADDR"=>"127.0.0.1", "REQUEST_METHOD"=>"POST", "REQUEST_PATH"=>"/task/screenshot", "PATH_INFO"=>"/task/screenshot", "REQUEST_URI"=>"/task/screenshot", "SERVER_PROTOCOL"=>"HTTP/1.1", "HTTP_VERSION"=>"HTTP/1.1", "HTTP_HOST"=>"localhost:3000", "HTTP_CONNECTION"=>"keep-alive", "CONTENT_LENGTH"=>"454856", "HTTP_ACCEPT"=>"application/json", "HTTP_ORIGIN"=>"null", "HTTP_USER_AGENT"=>"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) testivate-research-gigs/1.0.0 Chrome/49.0.2623.75 Electron/0.37.5 Safari/537.36", "HTTP_AUTHORIZATION"=>"Token token=redacted", "CONTENT_TYPE"=>"application/json", "HTTP_ACCEPT_ENCODING"=>"gzip, deflate", "HTTP_ACCEPT_LANGUAGE"=>"en-US", "rack.url_scheme"=>"http", "SERVER_NAME"=>"localhost", "SERVER_PORT"=>"3000", "QUERY_STRING"=>"", "rack.tempfiles"=>[#<Unicorn::TmpIO:/var/folders/k9/vnpft_6d7qs6xmdb9_4svvmw0000gn/T/0.19309304750270062>], "rack.input"=>#<Rack::Lint::InputWrapper:0x007fe1de317000 @input=#<Unicorn::TeeInput:0x007fe1de31d950 @len=454856, @chunked=false, @socket=#<Kgio::Socket:fd 7>, @parser=#<Unicorn::HttpParser:0x007fe1db08ce00>, @buf="", @rbuf="------WebKitFormBoundaryxkkhvE17qoI5ozlK\r\nContent-Disposition: form-data; name=\"img\"\r\n\r\ndata:image/jpeg;base64,iVBORw0KGgoAAAANSUhEU...

But I can't get to the image. This is what I see when I drop into the controller using Pry:

> request.body.read > request.body.rewind > request.body.read > request.env 

That is, I receive empty responses to most of the commands, and then it just hangs there indefinitely after I type request.env, without returning to the prompt.

How do I get to the image?

Thanks.

BTW, other actions that are receiving POSTs but not with embedded images are working perfectly. Previously, this action was working perfectly too when I was using XMLHttpRequest() not fetch(), but I've had to make the switch to turn my Google Chrome Extension into an Electron app.

UPDATE

I solved this problem for myself by uploading my images directly to S3 rather than to S3-via-Rails. It not only works but is faster than going via the app, which I now only have to tell where to look to find the image. But seeing as my original issue was not addressed, I'm leaving this question and the bounty open. Perhaps someone will solve it, claim the bounty, and write up an answer that someone else will find useful down the track.

2 Answers

Answers 1

If you are sending the image properly with POST and have it on the permitted params it should be available through regular parameters collection, then you can read your base64 encoded image and write it out:

File.open('some/path/to/image.jpg', 'wb') do|f|   f.write(Base64.decode64(base_64_encoded_data)) end 

Why are you reading from request.body directly anyway? params in your controller should have a hash of values from the form data.

Answers 2

I would test by sending a request from the desktop app to a locally served version of the API (i.e. run rails server from the terminal) and watch the rails console to see what is received. You should see a list of params. If the img param is included in the request then you are probably blacklisting via strong params in your rails controller

If you don't see the img param then you need to tweak the desktop app to send the form data correctly

Also, I suspect you should be using a post not a fetch from the desktop app

Read More

Saturday, April 9, 2016

Electron Builder Code Signing Download Certificate Error

Leave a Comment

I'm building an Electron app and using the npm package electron-builder to build the app and installer for Windows. I'm trying to use the CSC_LINK and CSC_KEY_PASSWORD environment variables to sign the app as described here: https://github.com/electron-userland/electron-builder#travis-appveyor-and-other-ci-servers

On first try the error and stack trace is:

Unhandled rejection Error: unable to verify the first certificate at Error (native) at TLSSocket.<anonymous> (_tls_wrap.js:1065:38) at emitNone (events.js:80:13) at TLSSocket.emit (events.js:179:7) at TLSSocket._init.ssl.onclienthello.ssl.oncertcb.TLSSocket._finishInit (_tls_wrap.js:593:8) at TLSWrap.ssl.onclienthello.ssl.oncertcb.ssl.onnewsession.ssl.onhandshakedone (_tls_wrap.js:425:38) From previous event: at Object.downloadCertificate (C:\projects\presentation\Electron\node_modules\electron-builder\src\codeSign.ts:97:18) ... 

I then tried setting the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 and now get a different error:

Unhandled rejection Error: Request error, status 400: Bad Request at ClientRequest.<anonymous> (C:\projects\presentation\Electron\node_modules\electron-builder\src\httpRequest.ts:36:16) ... 

The particular line that is being called in electron-builder's httpRequest.ts appears to just be using Node's https module: https.request(...) https://github.com/electron-userland/electron-builder/blob/master/src/httpRequest.ts#L28

This leads me to believe there is something up with the Windows machine or certificates. I'm running this on Windows 10, node 5.9.0.

2 Answers

Answers 1

It is better to file issue to https://github.com/electron-userland/electron-builder/issues directly to get answer from the maintainers. I am active current maintainer and don't check SO, so, unlikely that you get answer quickly ;)

If issue still actual for you, file issue :)

Answers 2

Not certain what the root of the issue was however I was able to get everything to work by moving the file to Dropbox. I still had to set NODE_TLS_REJECT_UNAUTHORIZED=0 and CSC_LINK needed to be set without quotes:

Success: SET CSC_LINK=https://www.dropbox.com/s/path/to/file.p12?dl=1

Failed: SET CSC_LINK="https://www.dropbox.com/s/path/to/file.p12?dl=1"

A link to the issue discussion on electron-builder GitHub can be found here: https://github.com/electron-userland/electron-builder/issues/291

Read More

Friday, April 8, 2016

'Unknown stdin file type' error in windows

Leave a Comment

I've been struggling with this errors for 2 days and can't realize why electron renderer process.stdin fails in windows os.

How to reproduce:

type npm install devtool -g then type devtool inside the console type process.stdin and there will be an error message will be two errors, one at line 127 and the other at line 128 at C:\Users\rafael\AppData\Roaming\npm\node_modules\devtool\node_modules\electron-prebuilt\dist\resources\atom.asar\renderer\lib\init.js(devtool update 2.x)

Error: Implement me. Unknown stdin file type!

C:\Users\rafael\AppData\Roaming\npm\node_modules\devtool\node_modules\electron-prebuilt\dist\resour…:127 Error: Implement me. Unknown stdin file type!(…)(anonymous function) @ C:\Users\rafael\AppData\Roaming\npm\node_modules\devtool\node_modules\electron-prebuilt\dist\resour…:127Module._compile @ module.js:425Module._extensions..js @ module.js:432Module.load @ module.js:356Module._load @ module.js:313Module.runMain @ module.js:457startup @ node.js:151(anonymous function) @ node.js:1007 C:\Users\rafael\AppData\Roaming\npm\node_modules\devtool\node_modules\electron-prebuilt\dist\resour…:128 Error: Implement me. Unknown stdin file type! at process.stdin (node.js:747) at hookProcess (C:\Users\rafael\AppData\Roaming\npm\node_modules\devtool\lib\preload.js:117) at C:\Users\rafael\AppData\Roaming\npm\node_modules\devtool\lib\preload.js:29 at Object.<anonymous> (C:\Users\rafael\AppData\Roaming\npm\node_modules\devtool\lib\preload.js:129) at Module._compile (module.js:425) at Object.Module._extensions..js (module.js:432) at Module.load (module.js:356) at Function.Module._load (module.js:313) at Module.require (module.js:366) at require (module.js:385)(anonymous function) @ C:\Users\rafael\AppData\Roaming\npm\node_modules\devtool\node_modules\electron-prebuilt\dist\resour…:128Module._compile @ module.js:425Module._extensions..js @ module.js:432Module.load @ module.js:356Module._load @ module.js:313Module.runMain @ module.js:457startup @ node.js:151(anonymous function) @ node.js:1007

3 Answers

Answers 1

I encountered the same problem.

First I thought that devtool as REPL does not need stdin and was a simple bug in windows build. GitHub repo owners fix it just ignoring stdin on startup but, as you had discovered, devtool is broken and you can not do anything with stdin in windows.

As a proof of concept I create a simple example beyond devtool REPL:

This piece of code does not work.

//test.js var readline = require('readline'); var rl = readline.createInterface({   input: process.stdin,   output: process.stdout,   terminal: true });  rl.on('line', function(line){     console.log(line); }) 

devtool test.js < input.txt

Error: Implement me. Unknown stdin file type! 

Windows 7 x64, S.O. Admin rights, Node v5.10.0, npm v3.8.3 DevTool v1.9.1.

I had left a comment in your github issue but is closed so I opened a new one.

Answers 2

There is another question pointing to the same problem. One of the comments states that it's a known iisnode issue and also suggests a work around by wrapping all calls to process.stdin like:

if(!process.env.IISNODE_VERSION) {      // do stuff with process.stdin  } 

It can be a temporary solution. I'm sure you've already taken a look to that post, what do you think?

Answers 3

Reading through the libuv source code which is what nodejs uses for certain low-level operations, seems that the reason is that the type of buffer or handle cannot be determined specifically for windows. The GetFileType function seems to return an unknown handle.

This is definitely a windows only issue because the part of the library that determines the type of handle is within src/win/handle.c of the UV source code so I don't think this affects *NIX OS'es indeed.

Maybe the installed nodejs version is missing a build-time option?

Read More

Friday, April 1, 2016

Unexpected token import on Electron app

Leave a Comment

I have built an app using GitHub's Electron. I am using the recommended way of loading modules, the ES6 syntax of:

import os from 'os'

After downloading the boilerplate the app is working fine. I have been able to import scripts in the background.js file without issue. Below is how I am loading my custom module:

import { loadDb } from './assets/scripts/database.js';

However, when I open a new browser window (clipboard.html) within Electron I am then loading a JavaScript file (clipboard.js) which in turn tries to import modules. At this point I am getting an Unexpected token import error.

My clipboard.html:

<!doctype html> <html> <head>     <meta charset="utf-8">     <title>Electron Boilerplate</title>      <link href="./stylesheets/main.css" rel="stylesheet" type="text/css">      <script>         window.$ = window.jQuery = require('./assets/scripts/jquery-1.12.1.min.js');     </script>     <script src="./assets/scripts/clipboard.js"></script> </head> <body class="clipboard">[...]</body></html> 

My clipboard.js file:

import { remote } from 'electron'; // native electron module import { loadDb } from './assets/scripts/database.js';  const electron = require('electron');  document.addEventListener('DOMContentLoaded', function () {      var db = loadDb();     db.find({ type: 'text/plain' }, function (err, docs) {         var docsjson = JSON.stringify(docs);         console.log(docsjson);     }); }); 

Just to re-iterate, the same code is used within app.html, which is my app's main window, and this does not error.

It feels like the main window is initialising something that my clipboard.html window isn't (perhaps 'Rollup'?), but there's nothing explicit within my app's code to suggest this.

2 Answers

Answers 1

You need to run clipboard.js through rollup first. Rollup parses the import statements. You have to modify tasks/build/build.js to do that.

var bundleApplication = function () {     return Q.all([             bundle(srcDir.path('background.js'), destDir.path('background.js')),             bundle(srcDir.path('clipboard.js'), destDir.path('clipboard.js')), // Add this line             bundle(srcDir.path('app.js'), destDir.path('app.js')),         ]); }; 

Answers 2

@user104317 got it right, clipboard.js just didn't get "compiled" by rollup.

Just wanted to add that in your case, it should have been:

var bundleApplication = function () {     return Q.all([         bundle(srcDir.path('background.js'), destDir.path('background.js')),         bundle(srcDir.path('app.js'), destDir.path('app.js')),         bundle(srcDir.path('assets/scripts/clipboard.js'), destDir.path('assets/scripts/clipboard.js')),     ]); }; 

Then you could have left it at ./assets/scripts/clipboard.js.

If you end up having a lot of independent js files (you shouldn't if you're building a SPA), consider listing them automatically, like done in ./tasks/build/generate_spec_imports.js

Read More