2017-10-04 44 views
1

我有一个电子应用程序,打开一个浏览器窗口与某个网页。 现在,我想在该页面上执行一些JavaScript作为第一件事。但无论我尝试什么,它似乎总是在我打开的网页上的其他JS之后运行。电子执行JavaScript作为页面上的第一件事

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

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

而且通过把它直接之后loadUrl

window.loadURL(url); 
window.webContents.executeJavaScript(`console.log('test');`); 

但在这两种情况下,之后其他一些JavaScript已经跑了test得到记录这一页。

+0

看起来你正试图在主进程中运行代码。这与渲染器进程中发生的任何事情无关。该页面正在渲染器进程中加载​​,并且您的did-start-loading在主进程中。 – shashi

+0

那么,webContents.executeJavaScript API是为了在主流程的渲染器进程中执行JavaScript。所以我试图(从主进程)在渲染器进程加载的页面上执行一些JavaScript,但在该页面上现有的任何JavaScript运行之前。 –

回答

0

当您创建浏览器窗口时,请包含一个预加载脚本。例如,

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

这里的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 . 
    */ 

让我知道你的作品!

相关问题