標籤:html5 html
譯文來源:http://www.ido321.com/1130.html
原文:HTML 5 Notification
譯文:HTML 5 的訊息通知機制
譯者:dwqs
HTML 5 已經被應用到Web開發中。跟平常一樣,任何一個軟體新版本的發布都期待一些新的特性,這對HTML 5也不例外。為了僅僅通過HTML提高使用者互動,HTML 5已經提供了很多新的API。
是不是非常有趣呢?並且HTML 5已經和CSS 3結合的非常棒了。
因此,我也開始寫一系列與HTML 5的API相關的文章來介紹API的使用和功能,例如Geolocation, Notification, File, 等等,第一篇文章是和Notification API相關。
首先要意識到是,HTML 5的特性和API僅能在支援HTML 5的瀏覽器中正常使用,如果瀏覽器不支援HTML 5,就不能使用HTML 5在網頁中實現任何一個功能了。現在就來瞭解一下notification API吧。
什麼是HTML 訊息通知?
HTML訊息通知是指我們可以告訴使用者一個確定的事件行為,即使此時使用者在瀏覽器的另一個選項卡。這個通知對於New Mail, New Tweet等事件是非常有用的。
怎麼使用?
要使用Notification API,有幾個步驟:首先,要從使用者那裡擷取顯示通知的許可,只有當使用者允許時,才能顯示通知給使用者。所以先要徵求使用者的許可而不是直接顯示通知。然後,
擷取使用者許可之後,我們可以顯示兩種類型的資訊:
- Normal/Default Notification
- HTML Notification
最後執行通知代碼。
我已經建立了一個顯示通知的JavaScript函數,注意:函數僅限用於這篇文章,因為有很多種方式可以按照每個人的需求去擴充。
HTML:
<h2>Show Normal Notification</h2><button class="btn btn-success" id="show_notification"> Normal Notification</button> <h2>Show HTML Notification</h2><button class="btn btn-success" id="show_html_notification"> HTML Notification</button>
JavaScript
// Function to show Notificationfunction createNotification(type){ if(type == ‘‘) type = ‘normal‘; if(type != ‘html‘) { var title ="You have received HTML 5 Notification"; var msg="Content Goes Here......"; var notification = window.Notifications.createNotification("1.png", title, msg); } else { var notification = window.Notifications.createHTMLNotification(‘content.html‘); } notification.show();}// Binding the Click event on buttons.$(document).ready(function (){ if (window.webkitNotifications) { window.Notifications = window.webkitNotifications; $(‘#show_notification‘).click(function () { if (window.Notifications.checkPermission() == 0) { createNotification(‘normal‘); } else { window.Notifications.requestPermission(); } }); $(‘#show_html_notification‘).click(function () { if (window.Notifications.checkPermission() == 0) { createNotification(‘html‘); } else { window.Notifications.requestPermission(); } }); } else { alert(‘HTML 5 Notifications are not supported on this browser/OS.‘); }});
Demo 查看Demo: live demo (ps:用Web Kit瀏覽器開啟,此文寫於2012.04) 總結 HTML 5 notification適用於像Google Chrome一樣的Web Kit瀏覽器,對於HTML 5 notification,Mozilla Firefox有其自己的私人屬性。我將在其它文章中介紹。
下一篇:Ajax非同步請求PHP資料
雜談:HTML 5的訊息通知機制