ricardolobo ricardolobo - 1 year ago 134
jQuery Question

How do I call an Electron API method from the renderer process?

I've been trying http://electron.atom.io for a while. I followed the http://electron.atom.io/docs/tutorial/quick-start/ and with relative success I managed to make an "app" using Bootstrap and Jquery.

But now, I'm trying to use Electron API methods but with no success.

I created a Browser Window, and within that Window I added a new JS file. Within that file, I'm trying to call printToPDF method here: http://electron.atom.io/docs/api/web-contents/#contentsprinttopdfoptions-callback

It just doesn't work and the console logs the following:

Uncaught ReferenceError: mainWindow is not defined

The code goes as this:


const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

let mainWindow

function createWindow () {
mainWindow = new BrowserWindow({width: 800, height: 600})

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

app.on('ready', createWindow)

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

app.on('activate', function () {
if (mainWindow === null) {


<!DOCTYPE html>
<meta charset="UTF-8">
<title>Hello World!</title>
<link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css">

<script>window.$ = window.jQuery = require('jquery');</script>
<script type="text/javascript" src="./js/bootstrap.min.js"></script>


$(function() {

Answer Source

Take a look at the ipc modules, ipcMain and ipcRenderer. The ipc module allows you to send and receive synchronous and asynchronous messages between the main and the render process.

Here the print to PDF example from the ELECTRON API DEMOS app.

Renderer Process

const ipc = require('electron').ipcRenderer

const printPDFBtn = document.getElementById('print-pdf')

printPDFBtn.addEventListener('click', function (event) {

ipc.on('wrote-pdf', function (event, path) {
  const message = `Wrote PDF to: ${path}`
  document.getElementById('pdf-path').innerHTML = message

Main Process

const fs = require('fs')
const os = require('os')
const path = require('path')
const electron = require('electron')
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
const shell = electron.shell

ipc.on('print-to-pdf', function (event) {
  const pdfPath = path.join(os.tmpdir(), 'print.pdf')
  const win = BrowserWindow.fromWebContents(event.sender)
  // Use default printing options
  win.webContents.printToPDF({}, function (error, data) {
    if (error) throw error
    fs.writeFile(pdfPath, data, function (error) {
      if (error) {
        throw error
      shell.openExternal('file://' + pdfPath)
      event.sender.send('wrote-pdf', pdfPath)