Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Javascript API extend application caching and server-side messages and desktop notifications in HTML5

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how Javascript API in HTML5 extends the application cache and server messages and desktop notifications. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

Application caching and server-side messages are supported in other major browsers. Desktop notifications are currently only supported by Chrome.

Application caching

In many cases, we need to cache pages that change infrequently to improve access speed, and for some applications, we also want to be able to use them offline. In HTML5, you can easily implement these functions through a technique called "application caching".

In the implementation of application caching, HTML5 allows us to create a cached manifest file to easily generate an offline version of the application.

Implementation steps:

1. To enable page caching, it is simple to include the manifest attribute in the html of document:

The code is as follows:

...

Every page that contains this manifest attribute is cached when the user visits it. If the manifest attribute is not specified, it will not be cached (unless the page is specified directly in the manifest file). There is no uniform standard for manifest file extension, and the recommended extension is ".appcache".

two。 Server-side configuration MIME type of manifest file

A manifest file needs to be supported by the correct MIME-type, and the file type is "text/cache-manifest". It must be configured on the web server you are using. For example: AddType text/cache-manifest manifest can be added to .htaccess in Apache.

3. Write manifest files

The manifest file is a simple text file that tells the browser what to cache (or what not to cache).

The manifest file contains the following three sections:

CACHE MANIFEST-Files under the heading of this list will be cached after download.

NETWORK-Files under the heading of this list will require a connection to the server and will not be cached.

FALLBACK-A specific page is displayed if the file under the heading of this list is not accessible.

A complete file is shown in the following example:

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:

The representative comment at the beginning of #.

* can be used to represent all other resources or files. For example:

The code is as follows:

NETWORK:

*

Indicates that all resources or files are not cached.

4. Update cach

Once an application is cached, it will remain cached unless the following occurs:

The user deleted the cache

The manifest file was modified

The application cache is modified by the program

So once the file is cached, except for artificial modifications, the browser will continue to display the cached version of the content, even if you modify the server file. In order for the browser to update the cache, you have to modify the manifest file.

The line that starts with "#" is a comment line, but can have other uses. If your changes involve only one image or javascript function, those changes will not be re-cached. Updating dates and versions in comments is one way for browsers to re-cache your files

Browsers can cache data with many different size limits (some browsers allow 5m cached data).

The code is as follows:

Server message

Another frequently used scenario is: how do you let the client know when the data on the server changes? This in the previous practice is: the page to take the initiative to query the server side for updates. From the previous introduction, we know that two-way communication can be achieved using WebSocket. Here is another new feature in HTML5: server-side messages (Server-Sent Events).

In HTML5, the object that hosts this property is the EventSource object.

The steps to use are as follows:

1. It is well known to check the browser's support for EventSource objects:

The code is as follows:

If (typeof (EventSource)! = "undefined")

{

/ / Yes! Server-sent events support!

/ / Some code.

} else {

/ / Sorry! No server-sent events support..

}

two。 Sending message code on the server side

Sending update messages on the server side is simple: after setting the content-type header to "text/event-stream", you can send events. Take the ASP code as an example:

The code is as follows:

3. The receiving 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") [xss_clean] + = event.data + "

"

}

Code description:

Create an EventSource object that specifies the page URL to send updates (in this case, demo_see.jsp)

Each time an update is received, the onmessage event is triggered

When the onmessage time is triggered, the resulting data is set to the element of id= "result"

In addition to onmessage events, the EventSource object also has onerror events that handle errors, onopen events that establish connections, and so on.

Desktop Notification-quasi-HTML5 feature

The desktop notification feature allows browsers to notify users of messages even in a minimized state. This is the most natural combination with WebIM. Currently, however, the only browser that supports this feature is Chrome. Pop-up windows are something everyone hates, so you need the user's permission to turn on this feature.

The code is as follows:

Function RequestPermission (callback) {

Window.webkitNotifications.requestPermission (callback)

}

Function showNotification () {

/ / determine whether the browser supports notification through window.webkitNotifications

If (!! window.webkitNotifications) {

If (window.webkitNotifications.checkPermission () > 0) {

RequestPermission (showNotification)

} else {

Var notification = window.webkitNotifications.createNotification ("[imgurl]", "Title", "Body")

Notification.ondisplay = function () {

SetTimeout ('notification.cancel ()', 5000)

}

Notification.show ()

}

}

}

Open this page in the browser and you will see a message window that lasts 5 seconds popup in the lower right corner of the desktop.

This feature is easy to use, but in the process of actual operation, we should minimize the interference of notification function to users and minimize the occurrence of notification function.

Here are some experiences of online experts in doing this application:

1. Make sure there is only one notification when you receive multiple messages

This problem is easier to solve because the notification object has a property called "replaceId". When this property is specified, the previous pop-up window will be overwritten whenever the notification window with the same replaceId pops up. In the actual project, all pop-up windows are assigned the same replaceId. It is important to note, however, that this overriding behavior is only valid in the same domain.

two。 No notification will appear when the user is in the page where IM appears (the page is in Focus state)

The main problem is to determine whether the browser window is in the Focus state, and there seems to be no better way to listen to window's onfocus and onblur events. This is the way to record the Focus status of the window in the project, and then determine whether the pop-up window is based on the Focus status when the message arrives.

The code is as follows:

$(window). Bind ('blur', this.windowBlur). Bind (' focus', this.windowFocus)

The important thing to pay attention to when using this method is that the event point of event registration should be as forward as possible. If the registration is too late, it is easy to misjudge the status when the user opens the page and then leaves.

3. When a user uses multiple Tab to open multiple pages with IM, no notification will appear as long as one page is in the Focus state

State sharing among multiple pages can be achieved through local storage:

Modify the value of the specified key in the local storage to "focus" when the browser window Focus

Modify the value of the specified key in the local storage to "blur" when the browser window Blur.

It should be noted that when switching from one Tab to another Tab under Chrome, the Blur is more likely to be written to the storage than after Focus, so modifying the Focus state requires asynchronous processing.

The code is as follows:

/ * window on focus event * /

/ / delay is used to solve the problem of always letting Focus override the Blur events of other Tab when switching between multiple Tab

/ Note: if there is no Focus to document before clicking Tab, clicking Tab will not trigger Focus

SetTimeout (function () {

Storage.setItem ('kxchat_focus_win_state',' focus')

}, 100)

/ * window on blur event * /

Storage.setItem ('kxchat_focus_win_state',' blur')

After the above state sharing is implemented, after the new message arrives, you only need to check whether the value of 'kxchat_focus_win_state'' in the local storage is blur, and if it is blur, the pop-up window will pop up.

4. How to enable users to click on the notification floating layer to locate the specific chat window

The notification window supports event responses such as onclick, and the scope of the response function belongs to the page on which the window was created. The code is as follows:

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 response function of onclick belongs to the currently created page, so it is easy to interact with the current page. The above code realizes that clicking the pop-up window will jump to the corresponding browser window and open the IM window.

The related events on the page are often indeterminate, so our code should try not to assume that some events are triggered in a certain order. Such as the blur and focus events above

The above is how Javascript API in HTML5 extends application caching and server-side messages and desktop notifications. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report