UNPKG

2.35 kBJavaScriptView Raw
1
2!function(window, xhr) {
3 var auth, poll
4 , put = getName(window)
5
6 if (!put.a) {
7 put.b = getName(window.opener).a || sessionStorage.getItem("last")
8 put.c = document.referrer
9 }
10
11 // JSON.parse and sessionStorage IE8
12
13 Object.each(
14 { DELETE: "del", GET: 0, PATCH: 0, POST: 0, PUT:0 },
15 function(name, method) {
16 xhr[name || method.toLowerCase()] = xhr[method] = xhrReq.bind(null, method)
17 }
18 )
19
20 xhr.hello = function(data, next) {
21 xhr.put("/hello", function(err, json) {
22 auth = !err && json.authorization
23 if (!err && json.a) {
24 put.a = json.a
25 window.name = JSON.stringify(put)
26 }
27 if (next) {
28 next(err, json)
29 }
30 setTimeout(xhrPoll, 1500)
31 }, data)
32 }
33
34 /*, ws
35 try {
36 new WebSocket("ws" + location.protocol.slice(4) + "//" + location.host + "/events")
37 .addEventListener("open", function(ev) {
38 ws = this
39 ws.send(put)
40 })
41 } catch(e) {}
42 function wsReq(method, url, next, data) {
43 // Prior to version 11, Firefox only supported sending data as a string.
44 ws.send(JSON.stringify({method:method,url:url,data:data}))
45 }
46 */
47
48
49 function xhrReq(method, url, next, data) {
50 var req = xhr(method, url, function onResponse(err, txt) {
51 var body = (
52 req.getResponseHeader("Content-Type") == "application/json" ?
53 JSON.parse(txt) :
54 txt
55 )
56 if (err) {
57 View.emit("xhr:" + err, body, method, url, data, onResponse, xhrSend)
58 } else if (next) {
59 next(err, body, req)
60 }
61 })
62 xhrSend(req, data)
63 return req
64 }
65
66 function xhrSend(req, data) {
67 if (auth) {
68 req.setRequestHeader("Authorization", auth)
69 }
70 if (data) {
71 req.setRequestHeader("Content-Type", "application/json")
72 }
73 req.send(data ? JSON.stringify(data) : null)
74 }
75
76 function xhrPoll() {
77 if (auth) {
78 xhr.put("/events", pollHandler)
79 }
80 }
81
82 function pollHandler(err, res) {
83 var i = 0
84 , events = !err && (Array.isArray(res) ? res : res.events)
85 , len = events && events.length || 0
86
87 if (len) for (; i < len; ) {
88 try {
89 View.emit("event", events[i++])
90 } catch(e) {
91 console.error(e)
92 }
93 }
94
95 setTimeout(xhrPoll, err ? 6000 : 600)
96 }
97
98 function getName(a) {
99 try {
100 // RE against XSS
101 a = JSON.parse(a.name.match(/^{[\w:"]*}$/)[0])
102 } catch(e) {
103 a = {}
104 }
105 return a
106 }
107
108 El.on(window, "focus", onFocus)
109 function onFocus() {
110 sessionStorage.setItem("last", put.a)
111 }
112}(this, xhr)
113