Electron 将 javascript 作为页面上的第一件事执行

Seb*_*hof 5 javascript electron

我有一个电子应用程序,可以打开带有特定网页的浏览器窗口。现在,我想首先在该页面上执行一些 javascript。但无论我尝试什么,它似乎总是在我打开的网页上的其他一些 JS 之后运行。

我尝试了一些事件did-start-loading,例如:

window.webContents.on('did-start-loading', () => {
  window.webContents.executeJavaScript("console.log('test');");
})
Run Code Online (Sandbox Code Playgroud)

并将其直接放在loadUrl

window.loadURL(url);
window.webContents.executeJavaScript(`console.log('test');`);
Run Code Online (Sandbox Code Playgroud)

但在这两种情况下,test在页面上运行其他一些 javascript 后都会被记录。

Aje*_*jey 3

创建浏览器窗口时包括预加载脚本。前任。

mainWindow = new BrowserWindow({
  webPreferences: {
    preload: path.join(__dirname, 'renderer.js')
  }
});
Run Code Online (Sandbox Code Playgroud)

这里renderer.js是在该窗口的任何其他 js 文件之前加载的。

从源代码来看——

     /**
     * Specifies a script that will be loaded before other scripts run in the page.
     * This script will always have access to node APIs no matter whether node
     * integration is turned on or off. The value should be the absolute file path to
     * the script. When node integration is turned off, the preload script can
     * reintroduce Node global symbols back to the global scope. See example .
     */
Run Code Online (Sandbox Code Playgroud)

让我知道这是否有效!

  • 这不允许您运行像“executeJavaScript”这样的自定义代码。用例:例如从主进程加载 redux 状态。 (2认同)