我正在尝试创建单个实例 Electron应用。 我正在使用app.makeSingleInstance ,请参阅下面的示例。
中键点击的 SingleInstance 问题:
- 如果我第二次点击 app.exe,单实例就可以工作
- 如果我在应用程序内的链接上单击鼠标中键,则不起作用
我需要什么:
- 使 Electron 应用程序成为单一实例,并确保即使单击中键,它仍保持单一实例。
- 我不想在我的应用程序中强制禁用中键点击,因为在某些地方,我有一个在非链接项目上使用它们的用例
如何重现:
- 使用存储库:https://github.com/electron/electron-quick-start
- 用我的
index.html
和main.js
替换现有的,见下文 npm install
然后npm start
index.html:
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Hello World!</title></head>
<body>
<h1>app.makeSingleInstance()</h1>
<a href="$">Middle Click on it</a>
</body>
</html>
main.js
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')
let mainWindow
const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => {
if (myWindow) {
if (myWindow.isMinimized()) myWindow.restore()
myWindow.focus()
}
})
if (isSecondInstance) {
app.quit()
}
function createWindow () {
mainWindow = new BrowserWindow({width: 800, height: 600})
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))
mainWindow.on('closed', function () {
mainWindow = null
})
}
app.on('ready', createWindow)
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
if (mainWindow === null) {
createWindow()
}
})
最佳答案
中键单击不会创建应用程序的新实例,而是创建 BrowserWindow
的新实例。您可以使用auxclick
禁用a
(实际上是所有)元素上的中键单击。事件。
如果您不想将这些事件重定向到默认浏览器,则可以在主窗口的 HTML 中放置以下 JavaScript 来禁用链接元素上的中键单击:
// The following function will catch all non-left (middle and right) clicks
function handleNonLeftClick (e) {
// e.button will be 1 for the middle mouse button.
if (e.button === 1) {
// Check if it is a link (a) element; if so, prevent the execution.
if (e.target.tagName.toLowerCase() === "a") {
e.preventDefault();
}
}
}
window.onload = () => {
// Attach the listener to the whole document.
document.addEventListener("auxclick", handleNonLeftClick);
}
但是您也可以选择将中键单击事件重定向到标准浏览器,即通过 Electron 的 shell
模块:
// Require Electron's "shell" module
const { shell } = require("electron");
function handleNonLeftClick (e) {
// e.button will be 1 for the middle mouse button.
if (e.button === 1) {
// Check if it is a link (a) element; if so, prevent the execution.
if (e.target.tagName.toLowerCase() === "a") {
// Prevent the default action to fire...
e.preventDefault();
// ...and let the OS handle the URL.
shell.openExternal(e.target.href);
}
}
}
// Also attach the listener this time:
window.onload = () => { document.addEventListener("auxclick", handleNonLeftClick); }
如果您还想阻止对 a
元素进行右键单击,则可以删除 if (e.button === 1)
。
关于node.js - Electron 通过中键单击防止多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49164924/