Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Electron Fiddle Gist
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Context Bridge Example</title>
<link rel="stylesheet" type="text/css" href="./styles.css">
</head>
<body>
<main class="app">
<button onclick="window.app.setFullscreen(true)">Enter fullscreen</button>
<button onclick="window.app.setFullscreen(false)">Exit fullscreen</button>
</main>
</body>
</html>
// Modules to control application life and create native browser window
const {app, BrowserWindow, ipcMain} = require('electron')
const path = require('path')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
allowRunningInsecureContent: false,
contextIsolation: true,
enableRemoteModule: false,
nodeIntegration: false,
sandbox: true,
preload: path.join(app.getAppPath(), 'preload.js'),
}
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
// Open the DevTools.
// mainWindow.webContents.openDevTools()
ipcMain.handle('setFullscreen', (event, flag) => {
if (mainWindow) {
mainWindow.setFullScreen(flag)
}
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
const { ipcRenderer, contextBridge } = require('electron')
contextBridge.exposeInMainWorld(
'app',
{
setFullscreen: (flag) => ipcRenderer.invoke('setFullscreen', flag),
}
)
.app {
text-align: center;
margin: 10rem;
}
@silveradd001

This comment has been minimized.

Copy link

@silveradd001 silveradd001 commented Jan 27, 2021

Hi Matt,

Thank you very much for the example and your article "Safer Electron apps with ContextBridge" was of help for my current endeavour with electron

There is one thing though that I do not get yet, how do you successfully use "require('./renderer.js')" in the index.html script section?

For me it always fails at execution time with the following error message:

Uncaught ReferenceError: require is not defined
at index.html:21

What I am trying to understand is; how do you successfully use the nodejs directive "require" in the inline script tag?

Other than this little detail, very nice explanation,

Thanks,

Alex.

@matt-allan

This comment has been minimized.

Copy link
Owner Author

@matt-allan matt-allan commented Jan 27, 2021

Oh sorry, that line and comment was added by default by Electron Fiddle and I didn't notice it. You can't use require because nodeIntegration is set to false. nodeIntegration enables all the modules you're trying to avoid with contextBridge so I would suggest keeping it disabling and specifying the APIs you need to use with contextBridge.exposeInMainWorld instead.

@silveradd001

This comment has been minimized.

Copy link

@silveradd001 silveradd001 commented Jan 27, 2021

Well now that does make sense indeed, otherwise, why disabling nodeIntegration if it is to be able to require node extensions ^^'

Anyway, thank you for coming back to me on this!

I wanted to make sure this was a typo and not something I didn't understand!

@raphael10-collab

This comment has been minimized.

Copy link

@raphael10-collab raphael10-collab commented Feb 11, 2021

@matt-allan
tried to follow your example and transpose it into an Electron-Typescript-React-Webpack app, but I'm encountering this problem: Cannot read property 'setFullscreen' of undefined :

preload.js :

const {
  contextBridge,
  ipcRenderer
} = require("electron")

contextBridge.exposeInMainWorld(
  "api", {
      {
        setFullscreen: (flag) => ipcRenderer.invoke('setFullscreen', flag),
      }
  }
)

global.ts :

export {}
declare global {
  interface Window {
    "api": {
      setFullscreen: (flag) => void;
    }
  }
}

main.ts :

let mainWindow: BrowserWindow;

const createWindow = (): void => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    height: 600,
    width: 800,
    backgroundColor: '#242424',
    webPreferences: {
      nodeIntegration: false,
      enableRemoteModule: false,
      contextIsolation: true,
      nodeIntegrationInWorker: false,
      nodeIntegrationInSubFrames: false,
      webSecurity: true,
      webviewTag: false,
      preload: './preload/preload',
      devTools: process.env.NODE_ENV !== 'production',
    },
  });
  mainWindow.webContents.openDevTools();

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

  ipcMain.handle('setFullscreen', (event, flag) => {
    if (mainWindow) {
      mainWindow.setFullScreen(flag);
    }
  });

  mainWindow.on('close', () => {
    console.log('Closing WindowTypeA...');
  });
}

in the renderer process App.tsx :

import * as React from 'react';
function App() {
  const toggleFullScreen = (flag: boolean) => {
    window.api.setFullscreen(flag);
  }

  return (
    <div className='container'>
      <h2 className='heading'>
          Multiple Selective Windows Communication
      </h2>
         <p>
           <button onClick={() => {
             toggleFullScreen(true);
             }}>Enter fullscreen</button>

           <button onClick={() => {
             toggleFullScreen(false);
             }}>Exit fullscreen</button>

         </p>
</div>

);

image

If I set in App.tsx :

const sendProxy = window.api.send;

I get the same error and the window is not rendered :

image

What am I doing wrongly? How to solve the problem?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment