ctenar
ctenar

Reputation: 808

How to call function defined in preload.js from renderer process in electron

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?

Upvotes: 3

Views: 1436

Answers (2)

Cyril Gupta
Cyril Gupta

Reputation: 13723

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

Upvotes: 0

ron
ron

Reputation: 157

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>

Upvotes: 4

Related Questions