Should I use Context Isolation with my Electron App

Tags: ,



My friend and I are almost done with our project. It’s basically a now playing/miniplayer app for Spotify. When I was checking the render process console, I had one more warning that I wanted to clear. It was about worldSafeExecuteJavaScript being true and how it’s unsafe. I looked farther in to it and it turns out I need to turn on contextIsolation too. I researched more and found out I have that I can’t use require in my render process. I tried looking up the documentation and I am confused. We want to make our app secure for the long run, especially since I’m in college and my friend working on it might get busy as his school ramps up; and also since contextIsolation will be true by default in Electron 12.

In our render processes javascript, we just need to require jQuery and ipcRenderer. How would we incorporate contextBridge (I think that’s what its called), to import jQuery and ipcRenderer into our javascript for the render process?

Answer

I got my application to work with contextIsolation on by using contextBridge. Here’s my main.js webPreferences with the preload script:

    webPreferences: {
      worldSafeExecuteJavaScript: true,
      contextIsolation: true,
      preload: path.join(__dirname, "preload.js")
    },

and here’s preload.js to import the ipcRenderer:

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

contextBridge.exposeInMainWorld(
    'ipcRenderer',
    {
/*
Important note: This will get it working, 
but I'm going to make multiple methods for 
each time I'm using this to heighten security.
https://www.electronjs.org/docs/tutorial/context-isolation#security-considerations
*/
      send: (channel, arg) => ipcRenderer.send(channel, arg),
      on: (event, data) => ipcRenderer.on(event, data)
    }
)

To import jQuery, I just imported it with index.html:

  <head>
    <meta charset="UTF-8">
    <title>Gemini</title>
    <meta http-equiv="Content-Security-Policy" content="script-src 'self'">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="macos.css">
    <script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script>
    <link rel="stylesheet" href="node_modules/@fortawesome/fontawesome-free/css/all.css">
  </head>

I’m not sure if importing jQuery through the HTML is safer though.



Source: stackoverflow