利用notification显示桌面通知
代码如下:
<template>
<div class="app-container">
<h1>Notification</h1>
<el-input
v-model="value"
style="width:300px;margin-right:20px;"
/>
<el-button @click="handleClick">显示Notify</el-button>
</div>
</template>
<script>
export default {
name: "index",
data() {
return {
value: '新的消息',
PERMISSON_GRANTED:'granted',
};
},
methods: {
async handleClick() {
// 创建一个消息提示
const notification = await this.createNotify(this.value, {
body: '你有新消息,请及时查看',
icon: '/xiaoxi.png', //public下的img的图片
data: 'https://www.baidu.com/',
});
// 处理点击事件
if (notification) {
notification.onclick = function (event) {
console.log(event);
};
}
},
async createNotify(title, options) {
// 如果用户已经允许,直接显示消息,如果不允许则提示用户授权
if (Notification.permission != this.PERMISSON_GRANTED) {
const res = await Notification.requestPermission(); //用于当前页面向用户申请显示通知的权限。这个方法只能被用户行为调用(比如:onclick 事件),并且不能被其他的方式调用。
}
if (Notification.permission == this.PERMISSON_GRANTED) {
return new Notification(title, options);
} else {
return null;
}
}
},
}
</script>
<style scoped>
</style>