【问题标题】:How to call function defined in preload.js from renderer process in electron如何从电子中的渲染器进程调用 preload.js 中定义的函数
【发布时间】:2021-04-26 04:41:56
【问题描述】:

this 的回答中,建议可以在preload.js 文件中定义一个javascript 函数并将其附加到window,然后从渲染器进程中调用(在包含的renderer.js 中或直接作为脚本在html 文件)使用window.functionName,即在preload.js

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

index.html:

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

但是,当我这样做并单击按钮时,我会收到错误消息 Uncaught TypeError: window.myFunction is not a function。 有人可以向我解释为什么会抛出这个错误以及如何定义函数吗?

【问题讨论】:

    标签: javascript electron


    【解决方案1】:

    使用Context IsolationcontextBridge

    Preload.js

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

    你的HTML.html

    <html>
        <head></head>
        <body>
            <script>
                window.YourAPI.yourFunction();
            </script>
        </body>
    </html>
    

    【讨论】:

      【解决方案2】:

      另一种无需使用 Bridge 方法即可解决此问题的方法是禁用 ContextIsolation,但现在不建议这样做以确保更好的安全性。

      但是,如果您有旧代码并且不想更改,您可以这样做。

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

      将 webPreferences 变量显式设置为 false。现在默认情况下,在较新版本的 Electron 中启用了 ContextIsolation

      【讨论】:

        猜你喜欢
        • 2021-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-03
        • 2019-04-11
        • 1970-01-01
        相关资源
        最近更新 更多