Flood HTML5 Javascript API extensions 5-Other extensions (Application Cache/Server messages/desktop notifications)

Source: Internet
Author: User

Comments: The main API extensions (Application Cache/Server Message/desktop notification) have been summarized earlier. The following are only available for specific scenarios, no IE support. Currently, desktop notifications are only supported by Chrome. If you are interested, you may find it helpful. The main API extensions have been summarized earlier, the following extensions play the biggest role only in special scenarios. Here is a brief introduction. None of the following features are supported by IE. Application caching and server messages are supported in other mainstream browsers. Currently, only Chrome supports desktop notifications.
Application Cache
Most of the time, we need to cache some infrequently changed pages to speed up access, and for some applications, we also hope to be able to use them offline. In HTML5, you can easily implement these functions through a technology called "application cache.
In the implementation of application cache, HTML5 allows us to create a cached manifest file to conveniently generate an offline version of the application.
Steps:
1. To enable page caching, you only need to include the manifest attribute in the html of the document:

The Code is as follows:
<! Doctype html>
<Html manifest = "demo. appcache">
...
</Html>

Every page containing this manifest attribute will be cached when the user accesses it. If the manifest attribute is not specified, it will not be cached (unless the webpage is directly specified in the manifest file ). There is no uniform standard for the manifest file extension. The recommended extension is ". appcache ".
2. Configure the MIME type of the manifest file on the server side
A manifest file must be supported by the correct MIME-type. The file type is "text/cache-manifest ". It must be configured on the web server in use. For example, you can add AddType text/cache-manifest to. htaccess in Apache.
3. Compile the manifest File
A manifest file is a simple text file that tells the browser what to cache (or not to cache ).
The manifest file contains the following three parts:
• Cache manifest-files under the title of this list will be cached after being downloaded.
• NETWORK-files under the title of this list are required to be connected to the server and will not be cached.
• FALLBACK-If files under the title of this list cannot be accessed, a specific page is displayed.
An example of a complete file is as follows:

The Code is as follows:
CACHE MANIFEST
#2012-02-21 v1.0.0
/Theme.css
/Logo.gif
/Main. js
NETWORK:
Login. asp
FALLBACK:
/Html5 // offline.html

Tip:
# Comments.
* It can be used to indicate all other resources or files. For example:

The Code is as follows:
NETWORK:
*

Indicates that all resources or files are not cached.
4. Update Cache
Once an application is cached, it will remain cached unless the following occurs:
• The user deleted the cache.
• Manifest File Modified
• The application cache is modified by the program
So once the file is cached, in addition to manual modification, the browser will continuously display the cached version content, even if you modify the Server File. To allow the browser to update the cache, you can only modify the manifest file.
: The line starting with "#" is a comment line, but it can be of other use. If your modifications only involve one image or javascript function, those changes will not be cached again. Updating the date and version in the annotations is a way for the browser to cache your files again.
: Browsers can cache a lot of data with different sizes (Some browsers allow 5 MB of cached data ).

The Code is as follows:
<Strong> Server Message </strong>
Another frequently used scenario is: how to let the client know when the data on the server changes? In the past, the page took the initiative to query whether the server has updates. According to the previous introduction, we know that WebSocket can implement bidirectional communication. Here we will introduce another new feature in HTML5: Server-Sent Events ).
In HTML5, the object carrying this feature is an EventSource object.
The procedure is as follows:
1. Check the support of the browser for the EventSource object. Everyone knows this:


The Code is as follows:
If (typeof (EventSource )! = "Undefined ")
{
// Yes! Server-sent events support!
// Some code .....
} Else {
// Sorry! No server-sent events support ..
}

2. Message sending code on the server side
Sending an update message on the server side is simple: After you set the content-type header to "text/event-stream", you can send events. Take ASP code as an example:

The Code is as follows:
<%
Response. ContentType = "text/event-stream"
Response. Expires =-1
Response. Write ("data:> server time" & now ())
Response. Flush ()
%>

3. Receive message code on the browser side

The Code is as follows:
Var source = new EventSource ("demo_sse.php ");
Source. onmessage = function (event ){
Document. getElementById ("result"). innerHTML + = event. data +"
";
};

Code Description:
• Create an EventSource object and specify the URL of the page for sending updates (demo_see.jsp)
• The onmessage event is triggered after each update is received
• When the onmessage time is triggered, set the obtained data to the element id = "result ".
In addition to onmessage events, EventSource objects also include onerror events for error handling and onopen events for connection establishment.
Desktop notification-quasi-HTML5 features
The desktop notification function allows the browser to send messages to users even in a minimal state. This is the most natural combination with WebIM. However, currently, only Chrome is supported. The pop-up window is a tough thing for everyone, so enabling this feature requires the user's permission.

The Code is as follows:
<Script>
Function RequestPermission (callback ){
Window. webkitNotifications. requestPermission (callback );
}
Function showNotification (){
// Determine whether the browser supports notification through window. webkitconfigurications
If (!! Window. webkitNotifications ){
If (window. webkitpolicications. checkPermission ()> 0 ){
RequestPermission (showNotification );
} Else {
Var notification = window. webkitNotifications. createNotification ("[imgurl]", "Title", "Body ");
Notification. ondisplay = function (){
SetTimeout ('notification. cancel () ', 5000 );
}
Notification. show ();
}
}
}
</Script>

Open this page in the browser and you will see a message window lasting 5 seconds in the lower right corner of the desktop.
This feature is easy to use, but in the actual operation process, we should try our best to reduce the interference of the notification function to users and minimize the emergence of the notification function.
The following are some experiences of online experts in this application.:
1. When receiving multiple messages, make sure only one notification appears;
This problem is better solved because the notification object has a property named "replaceId. After this attribute is specified, the previous pop-up window will be overwritten in the notification window with the same replaceId. In the actual project, the same replaceId is assigned to all the pop-up windows. However, it should be noted that this overwriting behavior is only valid in the same domain.
2. When a user is on an IM page (the page is in the Focus state), no notification will appear;
This problem mainly lies in determining whether the browser window is in the Focus state. Currently, in addition to listening to the onfocus and onblur events of the window, there seems to be no better way. In this way, the Focus status of the window is recorded in the project. When the message arrives, the Focus status is used to determine whether the window is displayed.

The Code is as follows:
$ (Window). bind ('blur', this. windowBlur). bind ('core', this. windowFocus );

When using this method, you must note that the event registration event points should be as high as possible. If the registration is too late, when the user opens the page and then leaves, it will be prone to misjudgment of the status.
3. When you use multiple tabs to open multiple pages with IM, no notification will appear if one page is in the Focus status;
Multi-Page Status sharing can be achieved through local storage:
• Change the value of the specified key in the local storage to "Focus" when you focus the browser window"
• In the browser window Blur, change the value of the specified key in the local storage to "blur ".
Note that when Chrome switches from one Tab to another, Blur may be written to the storage after the Focus, so it needs to be processed asynchronously when you modify the Focus status.

The Code is as follows:
/* Window on focus event */
// The latency is used to ensure that the Focus always overwrites the Blur events of other tabs when switching between multiple tabs.
// Note: if you do not Focus on the document before clicking the Tab, clicking the Tab will not trigger the Focus.
SetTimeout (function (){
Storage. setItem ('kxchat _ focus_win_state ', 'focal ');
},100 );
/* Window on blur event */
Storage. setItem ('kxchat _ focus_win_state ', 'blur ');

After the above State sharing is implemented, after a new message arrives, you only need to check whether the value of 'kxchat _ focus_win_state 'in the local storage is blur. If it is blur, the window is displayed.
4. How to let the user click the floating layer of the notification to locate the specific chat window
The notification window supports event responses such as onclick, and the scope of the response function is the page for creating the window. The following code:

The Code is as follows:
Var n = dn. createNotification (
Img,
Title,
Content
);
// Make sure there is only one reminder
N. replaceId = this. replaceId;
N. onclick = function (){
// Activate the browser window that pops up the Notification Window
Window. focus ();
// Open the IM window
WM. openWinByID (data );
// Close the Notification Window
N. cancel ();
};

The window object accessed in The onclick response function belongs to the currently created page, so it can easily interact with the current page. The above Code enables the pop-up window to jump to the corresponding browser window and open the IM window.
: The related events on the page are often time-ordered. Therefore, we should try not to assume that the order in which some events are triggered is certain. For example, the above blur and focus events

Practical reference:
Official documents: http://www.w3schools.com/html5/
Html5 a Chinese Tutorial: http://www.gbin1.com/tutorials/html5-tutorial/


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.