我正在制作单实例电子应用程序。我正在使用app.makeSingleInstance,请参阅下面的示例。
中键的 SingleInstance 问题:
我需要的:
如何重现:
index.html和替换现有的main.js,见下文npm install 进而 npm start索引.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>
Run Code Online (Sandbox Code Playgroud)
主文件
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()
}
})
Run Code Online (Sandbox Code Playgroud)
单击中键不会创建应用程序的新实例,而是创建BrowserWindow. 您可以a使用该auxclick事件禁用对(实际上是所有)元素的中间点击。
如果您不想将这些事件重定向到默认浏览器,您可以在主窗口的 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);
}
Run Code Online (Sandbox Code Playgroud)
但是你也可以选择将中间点击事件重定向到你的标准浏览器,即通过 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); }
Run Code Online (Sandbox Code Playgroud)
if (e.button === 1)如果您还想阻止对a元素的右键单击,则可以删除。
| 归档时间: |
|
| 查看次数: |
1710 次 |
| 最近记录: |