我正在测试Electron并专门使用executeJavaScript。我的项目使用POST请求登录网站,然后做一些工作并使用相同的会话加载第二个URL。在第二个URL中,我需要执行JS,但我不确定我做错了什么。
在这个例子中,我创建了一个愚蠢的版本,模拟转到两个URL并在第二个上执行JS。关于这里发生了什么的任何想法?
const {app, BrowserWindow} = require('electron');
let win;
function createWindow() {
win = new BrowserWindow({width: 1000, height: 600})
win.openDevTools();
// First URL
win.loadURL('https://www.google.com')
// Once dom-ready
win.webContents.once('dom-ready', () => {
// THIS WORKS!!!
win.webContents.executeJavaScript(`
console.log("This loads no problem!");
`)
// Second URL
win.loadURL('https://github.com/electron/electron');
// Once did-navigate seems to function fine
win.webContents.once('did-navigate', () => {
// THIS WORKS!!! So did-navigate is working!
console.log("Main view logs this no problem....");
// NOT WORKING!!! Why?
win.webContents.executeJavaScript(`
console.log("I canot see this nor the affects of the code below...");
const form = document.querySelectorAll('form.js-site-search-form')[0];
const input = form.querySelectorAll('input.header-search-input')[0]
input.value = 'docs';
form.submit();
`)
})
})
}
app.on('ready', createWindow );
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
答案 0 :(得分:3)
这是因为你试图在dom-ready事件之前运行Javascript。
尝试在此事件完成后执行您的javascript,如下所示
const { app, BrowserWindow } = require('electron');
let win;
function createWindow() {
win = new BrowserWindow({ width: 1000, height: 600 })
win.openDevTools();
// First URL
win.loadURL('https://www.google.com')
// Once dom-ready
win.webContents.once('dom-ready', () => {
// THIS WORKS!!!
win.webContents.executeJavaScript(`
console.log("This loads no problem!");
`)
// Second URL
win.loadURL('https://github.com/electron/electron');
// Once did-navigate seems to function fine
win.webContents.once('did-navigate', () => {
// THIS WORKS!!! So did-navigate is working!
console.log("Main view logs this no problem....");
win.webContents.once('dom-ready', () => {
// NOT WORKING!!! Why?
win.webContents.executeJavaScript(`
console.log("I canot see this nor the affects of the code below...");
const form = document.querySelectorAll('input.js-site-search-form')[0];
const input = form.querySelectorAll('input.header-search-input')[0]
input.value = 'docs';
form.submit();
`)
})
});
})
}
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});