2017-10-04 41 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 . 
    */ 

讓我知道你的作品!

相關問題