gpt4 book ai didi

javascript - Electron webContents执行JavaScript : Cannot execute script on second on loadURL

转载 作者:太空宇宙 更新时间:2023-11-04 03:26:52 32 4
gpt4 key购买 nike

我正在测试 Electron,特别是使用executeJavaScript。我的项目使用 POST 请求登录网站,然后执行一些工作并使用同一 session 加载第二个 URL。在第二个 URL 中,我需要执行 JS,但我不确定我做错了什么。

在这个例子中,我创建了一个简化版本,模拟访问两个 URL 并在第二个 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();
}
});

最佳答案

这是因为您尝试在 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();
}
});

关于javascript - Electron webContents执行JavaScript : Cannot execute script on second on loadURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43554536/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com