前言
使用官方文档里的Notification发起通知,无论主进程还是渲染进程都没有成功。如果是哪个地方写错了,希望大佬可以指出。
可以使用node-notifier来代替Notification实现通知的功能
主进程通知
主进程通知需要使用 Notification 模块
Notification是一个EventEmitter(事件触发与事件监听器功能的封装)
静态方法
Notification.isSupported()
:判断当前操作系统是否支持桌面通知,返回值是一个布尔值
Notification对象
new Notification([options])
:options可选参数,是一个对象,通知的配置项。常用的属性如下:
title: (String)标题
body: (String)通知的主题内容
silent: (Boolean)在显示通知时是否发出系统提示音
icon: (String)通知图标,
事件
show: 显示通知
click: 点击通知时触发
close: 手动关闭通知时触发,这个事件不能保证在所有情况下都会触发
const { app, BrowserWindow } = require('electron')
const reloader = require('electron-reloader')
const {Notification } =require('electron')
reloader(module)
const createWindow = () => {
//创建窗口
const mainWindow = new BrowserWindow({
width: 400,
height: 400,
webPreferences: {
// 开启node模块
nodeIntegration: true,
// 开启remote模块
enableRemoteModule: true,
//禁用上下文隔离
contextIsolation: false
}
})
//设置可以打开调试
mainWindow.webContents.openDevTools()
//加载要显示的路径
mainWindow.loadURL('http://localhost:3000/')
}
//通知
const sendNotification = () => {
console.log("Notification:",Notification.isSupported())
// 检查是否支持,Notification.isSupported()
if (Notification.isSupported()) {
let notification = new Notification({
title: '🌸',
body: 'Have a good day~'
})
console.log(notification.body)
notification.show()
} else {
console.log("不支持发送通知!")
}
}
app.whenReady().then(createWindow).then(()=>{
sendNotification()
})
不知道是不是哪里的问题,日志可以输出,但是通知就是不显示。
node-notifier
百度了一下,如果想在主进程中发起通知可以安装node-notifier
依赖
安装命令:
cnpm install --save node-notifier
基本使用如下:
// String
notifier.notify('Message');
//Object
const { app, BrowserWindow } = require('electron')
const reloader = require('electron-reloader')
const notifier = require('node-notifier');
const path = require('path');
reloader(module)
const createWindow = () => {
//创建窗口
const mainWindow = new BrowserWindow({
width: 400,
height: 400,
webPreferences: {
// 开启node模块
nodeIntegration: true,
// 开启remote模块
enableRemoteModule: true,
//禁用上下文隔离
contextIsolation: false
},
})
//设置可以打开调试
mainWindow.webContents.openDevTools()
//加载要显示的路径
mainWindow.loadURL('http://localhost:3000/')
}
app.whenReady().then(createWindow).then(()=>{
notifier.notify(
{
title:'消息提示', //通知的标题
message:'Hello world!', //通知的主体内容
icon: path.join(__dirname, '/public/logo512.png') ,//图标,通过path模块加载
sound:true, //是否显示提示音,true显示
},
function (err, response, metadata) {
})
})
运行结果:
渲染进程通知
渲染进程的通知,对象和方法与主进程一致,有细微的区别
实例: 点击按钮发起通知
import { Button } from 'element-react'
let style1 = {
margin: '30px'
}
//发送通知
let sendNotification = () => {
let notification = new Notification("通知", {
body: '通知的主体'
})
console.log(notification)
notification.onshow=()=>{
console.log("通知展示")
}
notification.onclick = () => {
console.log('通知被点击后触发')
}
}
const add = () => {
return (
<div style={style1}>
<Button type="primary" onClick={sendNotification.bind(this)}>点击</Button>
</div>
)
}
export default add;
真的服了,不知道是不是电脑的问题。通知就是不展示。从控制台可以看到,方法执行了
node-notifier方式
不知道啥原因,对象可以打印出来,显示通知时直接报错。不知道是不是电脑问题,改天换台电脑试一下。