3

In this answer it is suggested that a javascript function can be defined and attached to window in the preload.js file and then called from the renderer process (either in included renderer.js or directly as a script in the html file) using window.functionName, i.e. in preload.js:

window.myFunction = function(){
   //do something here that requires
   //ipcRenderer
} 

and in index.html:

<script>
   var myButton = document.getElementById("myButtonId")
   myButton.addEventListener('click', (e) => {
      window.myFunction();
});
</script>

However, when I do it like this and click the button, I get the error message Uncaught TypeError: window.myFunction is not a function. Can someone explain to me why this error is thrown and how to define the function instead?

ctenar
  • 718
  • 5
  • 24

2 Answers2

4

Use Context Isolation and contextBridge.

Preload.js

 const { contextBridge } = require('electron')
 contextBridge.exposeInMainWorld('YourAPI',
  {
    yourFunction: () => {'Your Codes.'}
  });

yourHTML.html

<html>
    <head></head>
    <body>
        <script>
            window.YourAPI.yourFunction();
        </script>
    </body>
</html>
ron
  • 157
  • 1
  • 6
0

Another way to resolve this without using having to use the Bridge method is by disabling ContextIsolation, though it is not advised now to ensure better security.

However, if you have legacy code and don't want to change, you can do this.

webPreferences: {
  contextIsolation: false,
  preload: path.join(__dirname, './preload.js'),
}

Set the webPreferences variable to false explicitly. By default now ContextIsolation is enabled in the newer versions of Electron

Cyril Gupta
  • 13,505
  • 11
  • 64
  • 87