1 // Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
2 // License: New BSD License
3 // Reference: http://dev.w3.org/html5/websockets/
4 // Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol
8 if ('undefined' == typeof window || window.WebSocket) return;
10 var console = window.console;
11 if (!console || !console.log || !console.error) {
12 console = {log: function(){ }, error: function(){ }};
15 if (!swfobject.hasFlashPlayerVersion("10.0.0")) {
16 console.error("Flash Player >= 10.0.0 is required.");
19 if (location.protocol == "file:") {
21 "WARNING: web-socket-js doesn't work in file:///... URL " +
22 "unless you set Flash Security Settings properly. " +
23 "Open the page via Web server i.e. http://...");
27 * This class represents a faux web socket.
29 * @param {array or string} protocols
30 * @param {string} proxyHost
31 * @param {int} proxyPort
32 * @param {string} headers
34 WebSocket = function(url, protocols, proxyHost, proxyPort, headers) {
36 self.__id = WebSocket.__nextId++;
37 WebSocket.__instances[self.__id] = self;
38 self.readyState = WebSocket.CONNECTING;
39 self.bufferedAmount = 0;
43 } else if (typeof protocols == "string") {
44 protocols = [protocols];
46 // Uses setTimeout() to make sure __createFlash() runs after the caller sets ws.onopen etc.
47 // Otherwise, when onopen fires immediately, onopen is called before it is set.
48 setTimeout(function() {
49 WebSocket.__addTask(function() {
50 WebSocket.__flash.create(
51 self.__id, url, protocols, proxyHost || null, proxyPort || 0, headers || null);
57 * Send data to the web socket.
58 * @param {string} data The data to send to the socket.
59 * @return {boolean} True for success, false for failure.
61 WebSocket.prototype.send = function(data) {
62 if (this.readyState == WebSocket.CONNECTING) {
63 throw "INVALID_STATE_ERR: Web Socket connection has not been established";
65 // We use encodeURIComponent() here, because FABridge doesn't work if
66 // the argument includes some characters. We don't use escape() here
68 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Functions#escape_and_unescape_Functions
69 // But it looks decodeURIComponent(encodeURIComponent(s)) doesn't
70 // preserve all Unicode characters either e.g. "\uffff" in Firefox.
71 // Note by wtritch: Hopefully this will not be necessary using ExternalInterface. Will require
72 // additional testing.
73 var result = WebSocket.__flash.send(this.__id, encodeURIComponent(data));
74 if (result < 0) { // success
77 this.bufferedAmount += result;
83 * Close this web socket gracefully.
85 WebSocket.prototype.close = function() {
86 if (this.readyState == WebSocket.CLOSED || this.readyState == WebSocket.CLOSING) {
89 this.readyState = WebSocket.CLOSING;
90 WebSocket.__flash.close(this.__id);
94 * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
96 * @param {string} type
97 * @param {function} listener
98 * @param {boolean} useCapture
101 WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
102 if (!(type in this.__events)) {
103 this.__events[type] = [];
105 this.__events[type].push(listener);
109 * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
111 * @param {string} type
112 * @param {function} listener
113 * @param {boolean} useCapture
116 WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
117 if (!(type in this.__events)) return;
118 var events = this.__events[type];
119 for (var i = events.length - 1; i >= 0; --i) {
120 if (events[i] === listener) {
128 * Implementation of {@link <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-registration">DOM 2 EventTarget Interface</a>}
130 * @param {Event} event
133 WebSocket.prototype.dispatchEvent = function(event) {
134 var events = this.__events[event.type] || [];
135 for (var i = 0; i < events.length; ++i) {
138 var handler = this["on" + event.type];
139 if (handler) handler(event);
143 * Handles an event from Flash.
144 * @param {Object} flashEvent
146 WebSocket.prototype.__handleEvent = function(flashEvent) {
147 if ("readyState" in flashEvent) {
148 this.readyState = flashEvent.readyState;
150 if ("protocol" in flashEvent) {
151 this.protocol = flashEvent.protocol;
155 if (flashEvent.type == "open" || flashEvent.type == "error") {
156 jsEvent = this.__createSimpleEvent(flashEvent.type);
157 } else if (flashEvent.type == "close") {
158 // TODO implement jsEvent.wasClean
159 jsEvent = this.__createSimpleEvent("close");
160 } else if (flashEvent.type == "message") {
161 var data = decodeURIComponent(flashEvent.message);
162 jsEvent = this.__createMessageEvent("message", data);
164 throw "unknown event type: " + flashEvent.type;
167 this.dispatchEvent(jsEvent);
170 WebSocket.prototype.__createSimpleEvent = function(type) {
171 if (document.createEvent && window.Event) {
172 var event = document.createEvent("Event");
173 event.initEvent(type, false, false);
176 return {type: type, bubbles: false, cancelable: false};
180 WebSocket.prototype.__createMessageEvent = function(type, data) {
181 if (document.createEvent && window.MessageEvent && !window.opera) {
182 var event = document.createEvent("MessageEvent");
183 event.initMessageEvent("message", false, false, data, null, null, window, null);
186 // IE and Opera, the latter one truncates the data parameter after any 0x00 bytes.
187 return {type: type, data: data, bubbles: false, cancelable: false};
192 * Define the WebSocket readyState enumeration.
194 WebSocket.CONNECTING = 0;
196 WebSocket.CLOSING = 2;
197 WebSocket.CLOSED = 3;
199 WebSocket.__flash = null;
200 WebSocket.__instances = {};
201 WebSocket.__tasks = [];
202 WebSocket.__nextId = 0;
205 * Load a new flash security policy file.
206 * @param {string} url
208 WebSocket.loadFlashPolicyFile = function(url){
209 WebSocket.__addTask(function() {
210 WebSocket.__flash.loadManualPolicyFile(url);
215 * Loads WebSocketMain.swf and creates WebSocketMain object in Flash.
217 WebSocket.__initialize = function() {
218 if (WebSocket.__flash) return;
220 if (WebSocket.__swfLocation) {
221 // For backword compatibility.
222 window.WEB_SOCKET_SWF_LOCATION = WebSocket.__swfLocation;
224 if (!window.WEB_SOCKET_SWF_LOCATION) {
225 console.error("[WebSocket] set WEB_SOCKET_SWF_LOCATION to location of WebSocketMain.swf");
228 var container = document.createElement("div");
229 container.id = "webSocketContainer";
230 // Hides Flash box. We cannot use display: none or visibility: hidden because it prevents
231 // Flash from loading at least in IE. So we move it out of the screen at (-100, -100).
232 // But this even doesn't work with Flash Lite (e.g. in Droid Incredible). So with Flash
233 // Lite, we put it at (0, 0). This shows 1x1 box visible at left-top corner but this is
234 // the best we can do as far as we know now.
235 container.style.position = "absolute";
236 if (WebSocket.__isFlashLite()) {
237 container.style.left = "0px";
238 container.style.top = "0px";
240 container.style.left = "-100px";
241 container.style.top = "-100px";
243 var holder = document.createElement("div");
244 holder.id = "webSocketFlash";
245 container.appendChild(holder);
246 document.body.appendChild(container);
247 // See this article for hasPriority:
248 // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html
250 WEB_SOCKET_SWF_LOCATION,
254 "10.0.0" /* SWF version */,
257 {hasPriority: true, swliveconnect : true, allowScriptAccess: "always"},
261 console.error("[WebSocket] swfobject.embedSWF failed");
267 * Called by Flash to notify JS that it's fully loaded and ready
270 WebSocket.__onFlashInitialized = function() {
271 // We need to set a timeout here to avoid round-trip calls
272 // to flash during the initialization process.
273 setTimeout(function() {
274 WebSocket.__flash = document.getElementById("webSocketFlash");
275 WebSocket.__flash.setCallerUrl(location.href);
276 WebSocket.__flash.setDebug(!!window.WEB_SOCKET_DEBUG);
277 for (var i = 0; i < WebSocket.__tasks.length; ++i) {
278 WebSocket.__tasks[i]();
280 WebSocket.__tasks = [];
285 * Called by Flash to notify WebSockets events are fired.
287 WebSocket.__onFlashEvent = function() {
288 setTimeout(function() {
290 // Gets events using receiveEvents() instead of getting it from event object
291 // of Flash event. This is to make sure to keep message order.
292 // It seems sometimes Flash events don't arrive in the same order as they are sent.
293 var events = WebSocket.__flash.receiveEvents();
294 for (var i = 0; i < events.length; ++i) {
295 WebSocket.__instances[events[i].webSocketId].__handleEvent(events[i]);
305 WebSocket.__log = function(message) {
306 console.log(decodeURIComponent(message));
310 WebSocket.__error = function(message) {
311 console.error(decodeURIComponent(message));
314 WebSocket.__addTask = function(task) {
315 if (WebSocket.__flash) {
318 WebSocket.__tasks.push(task);
323 * Test if the browser is running flash lite.
324 * @return {boolean} True if flash lite is running, false otherwise.
326 WebSocket.__isFlashLite = function() {
327 if (!window.navigator || !window.navigator.mimeTypes) {
330 var mimeType = window.navigator.mimeTypes["application/x-shockwave-flash"];
331 if (!mimeType || !mimeType.enabledPlugin || !mimeType.enabledPlugin.filename) {
334 return mimeType.enabledPlugin.filename.match(/flashlite/i) ? true : false;
337 if (!window.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION) {
338 if (window.addEventListener) {
339 window.addEventListener("load", function(){
340 WebSocket.__initialize();
343 window.attachEvent("onload", function(){
344 WebSocket.__initialize();