HTML5   发布时间:2022-04-25  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了HTML5 New Feature Series: Web Notifications大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

Recently,I did some researches on new technologies of HTML5,and I really want to write down @R_674_8270@ kNowledges I have leant,one hand,it can deepen my understanding of @R_674_8270@ new features,and on the other hand,I hope I can Help the beginners to understand and master them.

Then today we will tell something about the so-called 'Desktop Notification',that is the 'Web Notifications' tech.

'Web Notifications' is an exciTing new feature in HTML5,it allows developer to configure and show a desktop notification,and then to provide a better experience for user. Specially,users can receive a desktop message from page even though they are occupied with something else that unrelated with the page,and it can make users perceive some changes in the page. For instance,a mail notification from page will come when we're coding,or a new message from online chat when we're still coding,etc.

and then we will try to create our own notification step by step.

To create a notification,we need to create a message component first,and it's pretty simple,we can just use the Notification class to create an instance,it belongs to the 'window' object,so we can use it directly,just like this:

var n = new Notification("sir,you got a message",{
	icon: 'img/icon.png',body: 'you will have a meeTing 5 minutes later.'
});

There're two important parameters in the constructor of Notification: the first one is the message title,and the second is message content object,note that the object consists of two properties,they represent the icon and a message description respectively.

After the execution of the code,we will have created a notification instance successfully,and finally it will show up just like this in Chrome:

HTML5 New Feature Series: Web Notifications


Now we almost succeed,but whether it can show the message component depends on the permission user granted. In view of the security mechanism,our notification will not show up until user has granted. So currently what we need to do is to request the permission from user.

Fortunately,Notification provides us a great function to request permission,it's just called 'requestPermission',and it can perform just like this:

Notification.requestPermission(function(status) {
	//status is the current permission,if user allows notification,status should be 'granted'
	console.log('status: ' + status);

	//permission is a read-only property
	var permission = Notification.permission;
	//default user ignored our request or denied,the message will not show
	//granted user granted our request,the message can show
	//denied  user denied our request,the message will never show up

	console.log('permission: ' + permission);
});
When the codes are being executed,the browser will ask users whether they allow the notification of the current site,just like the following screenshot:

HTML5 New Feature Series: Web Notifications


If user clicks the left button,no matter how we run our codes,the notification will never appear,and only when user clicks the 'Allow' button,it can work.

Just like the description above,after the requestPermission's execution,the program will get into a callBACk function,and we can pass a parameter named 'status' into this function,it inDicates the final permission status after users make their choice. If user clicks the right close icon,that means user ignores this permission request,the status will be 'default',and the notification can not show under this condition. If user chooses the 'Block' button,we will get a 'denied' status,obvIoUsly,user denies the request,and naturally,the message notification will not come out. Lastly,if user clicks the 'Allow' button,the status will become 'granted',and the notification can show up perfectly in this condition.

@H_544_4@meanwhile,after the permission request is done,the browser will update the 'permission' property of Notification object and assign the current permission to it. Note that this property is read-only to developers,and its value is identical with the status we just mentioned above. So if we want to show a notification,we can detect whether we have the permission first:

if (Notification.permission === 'granted') {
	//show notification
}
Just as the codes described,we can show the notification when being sure the current permission is 'granted'. But just only a notification component is unattractive,it should have somE interactions,and also should have some events getTing involved. Luckily,the Notification has already defined a set of functions to process the events,and we can easily use them to complete our interaction:
var n = new Notification("sir,body: 'you will have a meeTing 5 minutes later.'
});

//onshow function will be invoked when notification is showing
n.onshow = function() {
	console.log('notification shows up');
	//close message notification 5 seconds later
	setTimeout(function() {
		n.close();
	},5000);
};

//when notification is being clicked,it will call onclick
//we can open the associated view and close the notification at the same time
n.onclick = function() {
	alert('open the associated view');
	//opening the view...
	n.close();
};

//onerror will be called when some errors occured
//not that it will call onerror if we insist on creaTing notification instance without granted permission
n.onerror = function() {
	console.log('notification encounters an error');
	//do something useful
};

//onclose will be invoked when a notification is closed
n.onclose = function() {
	console.log('notification is closed');
	//do something useful
};
As we can see,There are 4 useful functions that can be used to process interaction events,basically the events can be easily handled by mastering the usage of @R_674_8270@ functions.

At last,we will organize @R_674_8270@ steps together to create a simple example for a better demonstration with this feature.

And we create some folders and files:

HTML5 New Feature Series: Web Notifications


Then we organize the codes together to shape an object,just like the following codes:

var NotificationHandler = {
	isnotificationSupported: 'Notification' in window,isPermissionGranted: function() {
		return Notification.permission === 'granted';
	},requestPermission: function() {
		if (!this.isnotificationSupported) {
			console.log('the current browser does not support Notification API');
			return;
		}

		Notification.requestPermission(function(status) {
			//status is the current permission,if user allows notification,status should be 'granted'
			console.log('status: ' + status);

			//permission is a read-only property
			var permission = Notification.permission;
			//default user ignored our request or denied,the message will not show
			//granted user granted our request,the message can show
			//denied  user denied our request,the message will never show up

			console.log('permission: ' + permission);
		});
	},showNotification: function() {
		if (!this.isnotificationSupported) {
			console.log('the current browser does not support Notification API');
			return;
		}
		if (!this.isPermissionGranted()) {
			console.log('the current page has not been granted for notification');
			return;
		}

		var n = new Notification("sir,{
			icon: 'img/icon.png',body: 'you will have a meeTing 5 minutes later.'
		});

		//onshow function will be invoked when notification is showing
		n.onshow = function() {
			console.log('notification shows up');
			//close message notification 5 seconds later
			setTimeout(function() {
				n.close();
			},5000);
		};

		//when notification is being clicked,it will call onclick
		//we can open the associated view and close the notification at the same time
		n.onclick = function() {
			alert('open the associated view');
			//opening the view...
			n.close();
		};

		//onerror will be called when some errors occured
		//not that it will call onerror if we insist on creaTing notification instance without granted permission
		n.onerror = function() {
			console.log('notification encounters an error');
			//do something useful
		};

		//onclose will be invoked when a notification is closed
		n.onclose = function() {
			console.log('notification is closed');
			//do something useful
		};
	}
};

document.addEventListener('load',function() {
	//try to request permission when page has been loaded.
	NotificationHandler.requestPermission();
});
As we can see,the object has been created to manage the events that related with message,In general,our process is like this: execuTing the requestPermission function to ask user for granTing,and then we can call showNotification when we need to show a message,for example:
setTimeout(function() {
	//if there has new mail,show notification
	NotificationHandler.showNotification();
},5000);
Note that,not all browsers support Notification API,so we added a property named 'isnotificationSupported',which is used to tell whether the browser supports. And in the above codes,if it's detected that browser doesn't support this API,our program will return directly,instead of execuTing conTinuously,but in our real development,we can notify user in another way.

Then let's take a look at the index.html file:

<!DOCTYPE html>
<html>
	<body>
		<button onclick="NotificationHandler.showNotification()">show notification</button>
	</body>
	<script type="text/javascript" src="js/main.js"></script>
</html>
This file is pretty simple and clear,therefore we don't need to talk too much on it,let's take a glance at it:
1. Click the button to show a message,then close the message directly or wait 5 seconds,we will see two logs in the console panel:

HTML5 New Feature Series: Web Notifications

2. Click the button to show the message,and then click the message body,then an alert window will appear:

HTML5 New Feature Series: Web Notifications

Looks pretty nice,isn't it? Maybe it's a little complicated in real development,but if we understand the way how it runs,everything will be easier than we think.

In the end,there is an very important thing needs to be pointed out,a message can show up only when developers visit the page in a running web server,if they double-click the local file,it doesn't work at all. So when we practise,remember to put the whole directory into a web container.

Although Notification is a fantastic feature,we can't stop some sites from sending unfriendly messages,fortunately,user can remove the corresponding permission to disable the notification functionality. We can click the 'setTing' to open the setTing panel,and then click the 'show advanced setTing' at the bottom,then click the 'content setTing' under the 'privacy',and ultimately a window will come out,scroll down and we will find the 'notification',and then we all kNow what to do next.

Now,perhaps the most usages of Notification have been covered,and I hope all of us can learn it,then apply this featurE into our project,and if so,thE interaction will be more attractive to user.

大佬总结

以上是大佬教程为你收集整理的HTML5 New Feature Series: Web Notifications全部内容,希望文章能够帮你解决HTML5 New Feature Series: Web Notifications所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。