我有一个 Electron 应用程序,可以在添加一些额外功能的同时包裹一个远程页面。使用以下代码,页面将加载并运行。问题在于它缺少用于控制历史记录导航和页面缩放的常规浏览器快捷方式。
因此,我喜欢手动添加这些快捷方式。当找不到要附加事件监听器的远程页面的文档或窗口时,我失败了。
如何将keydown(和其他)事件监听器附加到远程页面?
const {app, shell, BrowserWindow} = require('electron');
let mainWindow;
function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1024,
height: 786,
});
mainWindow.setMenu(null);
mainWindow.setTitle('My app – Connecting…');
mainWindow.loadURL('https://some.url.somwhere');
mainWindow.webContents.on('did-finish-load', () => {
// How to get the window/document here? Both are undefined
window.addEventListener('keydown', (e) => {
if (e.key === 'ArrowLeft' && e.altKey) {
webview.history.back();
} else if (e.key === 'ArrowRight' && e.altKey) {
webview.history.forward();
}
});
});
// Emitted when the window is closed.
mainWindow.on('closed', () => {
mainWindow = null
})
}
app.on('ready', createWindow);
最佳答案
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.openDevTools()
mainWindow.webContents.executeJavaScript(`window.addEventListener('keydown', (e) => {
if (e.key === 'ArrowLeft' && e.altKey) {
console.log('Alt + <-')
window.history.back();
} else if (e.key === 'ArrowRight' && e.altKey) {
console.log('Alt + ->')
window.history.forward();
}
});`)
})
关于javascript - 如何在 Electron 应用程序中将监听器附加到远程页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868274/