【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')
}




猜你喜欢

转载自blog.csdn.net/qq_43058685/article/details/115126669