(原文見:http://www.xdarui.com/index.php/archives/111 )
本月18日W3C發布了一個新的草案《Push API》,原文見這裡:http://www.w3.org/TR/push-api/ 。不才鄙陋,目前只是一知半解。下面文叔給大家分享下這份草案,當然還是建議同學們直接無視本文而直接到W3C的原文地址學習。由於只是草案,同時的隨時都有可能被更新或替代或廢掉,誰知道明天是什麼樣呢。
關於PUSH
這塊的內容有兩位博主已經寫的很詳細了,我這裡直接帖出原文地址,沒有相關知識背景的同學可以移步這裡:1.手機Push機制 http://blog.163.com/fuhaocn@126/blog/static/36665080201204103631378/ 2.關於手機Push http://www.cnblogs.com/aspnethot/articles/2258724.html
Webapps Push
webapps是指當前很多WEB端網站已經脫離了簡單的展示或表單提交之類,如Gmail這種富前端應用已經上升到了一個應用程式只是這個應用程式是在WEB端而已,主要代碼由Javascript構成。好了不廢話,下面咱們直接聊正題。《Push API》草案旨在為WEB前端提供處理伺服器推送訊息能力。Push服務與 web應用的的活躍狀態無關。 Push訊息可以通過多種標準的協議分發(如SSE/GSM-SMS/SIP MESSAGE/OWA PUsh),或通過特定的瀏覽器方法。
PUSH的工作流程與移動手機端類似:首先,程式需要產生一個唯一的 Token ,然後使用這個ID由使用者顯示授權同意後web程式方可與伺服器建立push通道。
為了示範我就直接把W3C的樣本直接搬過來了:
EXAMPLE 1
var token = getGuid(); // get GUID as unique token
var mypush = requestRemotePermission(token);
mypush.onerror = function () {
alert("darn! "+e.message);
};
mypush.onsuccess = function () {
var activate = "http://example.com/push/activate?token="+token+
"&serviceUrl="+encodeURIComponent(mypush.serviceUrl)+
"&serverProtocols="+mypush.serverProtocols;
asyncXHR(activate); // send activation request to application server
mypush.wakeup = true;
mypush.onmessage = function (event) {
document.getElementById(‘message’).innerHTML = event.data;
};
};
按草案所述navigator需要實現NavigatorPush介面,這個介面定義了 push 屬性( readonly ) 。同時草案也定義了另一個介面:PushManager 。( 按草案所述應該是 window 會實現這個介面 )。PushManager提供了兩個方法:
checkRemotePermission和requestRemotePermission。 使用checkRemotePermission方法可以檢查當前 web應用是否已經得到了使用者授權(這個過程中不需要使用者操作介入),如果當前程式已經獲得授權則會調用 success回調否則執行 error 回調。success回調可以返回一個PullService對象( 與調用requestRemotePermission方法所擷取的一樣 )。requestRemotePermission首先會通過使用者代理程式(一般對我們來說是指瀏覽器了)詢問使用者是否授權,如果使用者同意那麼由程式產生的唯一Token就會成為Push服務的地址(目標服務),同時啟用Push服務。下面給出的是相關的IDL定義:
[NoInterfaceObject]
interface NavigatorPush {
readonly attribute PushManager push;
};
interface PushManager {
PushService requestRemotePermission (DOMString appToken, optionalDOMString publicKey, optional DOMString algorithm);
PushService checkRemotePermission (DOMString appToken);
};
PushService介面
web程式通過PushService介面處理Push服務。它的定義如下:
interface PushService : EventTarget {
readonly attribute DOMString appToken >;
readonly attribute DOMString publicKey;
readonly attribute DOMString algorithm;
readonly attribute DOMString serviceUrl;
readonly attribute DOMString[] serverProtocols;
readonly attribute DOMError error;
attribute boolean wakeup;
attribute Function? onsuccess;
attribute Function? onerror;
attribute Function? onmessage;
void close ();
readonly attribute unsigned short readyState;
const unsigned short CONNECTING = 0;
const unsigned short OPEN = 1;
const unsigned short CLOSED = 2;
};
說明:
1.如果多個web程式產生的Token一致,那麼發送到這個Token作為地址的Push訊息會同時發給這幾個執行個體。說通俗點就是如果A和B同時拿著票T去登記,那麼登記處在通知T可用的時候會同時通知A和B兩個。
2.為了驗證Push訊息的來源正確,應用服務可以對Push訊息進行簽名。如果這樣做則PushService應當有其相對應的publicKey及algorithm (演算法)。
3.Push服務與web程式是否活躍無關,同一個web程式也可以註冊多個push服務。同一個web程式的多個執行個體也可以各自註冊自己的push服務。