【Eelectron入门系列】(二)为你的应用添加一个消息通知功能

Electron提供了能让应用程序向用户发送消息通知的手段。可以在主进程和渲染进程中使用。(以Window为例,因为没有mac)

在开始之前,请先按照【Eelectron入门系列】(一)快速搭建一个Electron的Hello World项目创建一个Electron的项目。

创建好Electron的Hello World项目后,打开index.html文件检查一下,如果有以下两行代码,可以先删除了。加上了的话,是无法使用外部js代码


    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">

index.html中加入

    <script src="./renderer.js"></script>

渲染进程中的消息通知

renderer.js中添加下列代码


const myNotification = new Notification('Title', {
    body: 'Notification from the Renderer process'
})
myNotification.onclick = () => {
    console.log('Notification clicked')
}


运行项目

npm start

可以看到弹出的这个东西

在这里插入图片描述

点击之后,打开调试程序,可以看到打印的话

在这里插入图片描述

主进程中的消息通知

在主进程使用,则需要引入Notification模块
main.js中修改下列代码

// 引入 Notificaton模块
const { Notification } = require('electron')

// 创建一个通知
function showNotification() {
  new Notification({
    title:"main notification",
    body:"来自主进程中的通知"
  }).show()
}

// 当页面创建好后调用创建通知的函数
app.whenReady().then(() => {
  createWindow()
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
}).then(showNotification)


在这里插入图片描述

Notification的使用

修改应用名

在弹出的消息中可以发现最上方有个electron.app.ELectron的字样,这是模式的程序名,我们可以进行修改,
main.js


app.setAppUserModelId("我的Electron程序")

属性

title

字符串类型,通知的标题


  new Notification({
    title:"main notification",
    body:"来自主进程中的通知"
  })

subtitle

字符串类型,子标题


new Notification({
    title:"main notification",
    subtitle:"子标题",
    body:"来自主进程中的通知"
  })

body

字符串类型,消息的主体内容


new Notification({
    title:"main notification",
    subtitle:"子标题",
    body:"来自主进程中的通知"
  })

事件

常用的事件有:

  • click
  • show
  • close

创建一个notification对象后,进行赋值



const myNotification = new Notification('Title', {
    body: 'Notification from the Renderer process'
})
myNotification.onclick = () => {
    console.log('Notification clicked')
}




评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jiangxiaoju

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值