Как я могу открыть страницу, нажав на уведомление, используя электрон
Я разрабатывал приложение, которое создает оповещение / уведомление через сокет-сервер. Поэтому я сделал следующие компоненты для реализации того же.
Сокет-сервер с узлом-уведомителем
Электронное приложение
Здесь я получаю уведомления без каких-либо проблем. Но когда я нажимаю на уведомление, оно не идет внутрь следующей части кода. Поэтому я не могу обрабатывать такие события, как щелчок, закрытие и т. Д.
top.notification.on("click", ev =>{
console.log("User Clicked on Notification");
});
Мой файл index.js, используемый для приложения Electron, выглядит следующим образом.
"use strict";
const appId = "com.myapp.id";
const {
app,
nativeImage,
Tray,
Menu,
BrowserWindow,
Notification
} = require("electron");
app.setAppUserModelId(appId);
let top = {}; // prevent gc to keep windows
app.once("ready", ev => {
top.win = new BrowserWindow({
width: 800,
height: 600,
center: true,
minimizable: true,
show: true,
webPreferences: {
nodeIntegration: false,
webSecurity: true,
sandbox: true,
},
});
top.win.loadURL("http://localhost:4200");
top.win.on("close", ev => {
//console.log(ev);
ev.sender.hide();
ev.preventDefault();
});
top.notification = new Notification('Title', {
body: 'Lorem Ipsum Dolor Sit Amet'
});
top.notification.on("click", ev => {
console.log("User Clicked on Notification");
});
});
app.on("before-quit", ev => {
top.win.removeAllListeners("close");
top = null;
});
Код сокет-сервера, как показано ниже
let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let not = require('node-notifier');
io.on('connection', (socket) => {
var userId = Math.floor(Math.random() * 100)
// Log whenever a user connects
console.log(userId, 'user connected');
var alert = new Object();
alert.name = 'fire at backyard';
alert.details = 'fire at backyard hometown location :lat:1.23424 lang:123434';
alert.createdBy = 'User';
alert.createdDate = new Date();
// Log whenever a client disconnects from our websocket server
socket.on('disconnect', function() {
console.log(userId, 'user disconnected');
});
// When we receive a 'message' event from our client, print out
// the contents of that message and then echo it back to our client
// using `io.emit()`
socket.on('message', (message) => {
alert.name = message;
io.emit('alertGenerated', alert);
not.notify({
title: 'My notification',
message: 'Hello, there!',
appId: "com.myapp.id"
});
console.log("Message send by socket", userId, ":", alert.name);
});
});
// Initialize our websocket server on port 5000
http.listen(8000, () => {
console.log('started on port 8000');
});
Пожалуйста, помогите мне обработать события уведомления для моих уведомлений рабочего стола Windows в среде Electron.
0 ответов
Если я правильно понимаю ваш вопрос, Electron использует тот же API уведомлений, что и браузеры, для отображения уведомлений на рабочем столе.
Таким образом, чтобы управлять событием щелчка (например, открытием нового окна), вы можете создать уведомление и добавить слушателя к событию щелчка. В моем случае я открываю новое окно, используя
newNotification = new Notification('Hi, this is a notification');
newNotification .onclick = function (event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open("google.com","_blank");
};
См. https://www.electronjs.org/docs/api/window-open для получения подробной информации об Electron.
window.open()