-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
99 lines (84 loc) · 2.46 KB
/
Copy pathindex.js
File metadata and controls
99 lines (84 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var EventEmitter = require('events').EventEmitter;
var json = typeof JSON === 'object' ? JSON : require('jsonify');
var proto = require('dnode-protocol');
var bus = require('postmessage');
module.exports = function (opts, vars, cb) {
if (typeof opts === 'string') {
opts = { uri : opts };
}
if (typeof cb === 'object') {
var cb_ = cb;
cb = vars;
vars = cb_;
}
if (!vars) vars = {};
var w = new Driver(opts, vars);
if (typeof cb === 'function') w.next(cb);
return w;
};
function Driver (opts, vars) {
var self = this;
self.vars = vars;
self.element = document.createElement('iframe');
var queue = self.queue = { next : [], remote : [] };
self.client = proto(function (remote, conn) {
conn.on('ready', function () {
if (queue.next.length) {
var cb = queue.next.shift();
remote.run(String(cb), vars);
}
else queue.remote.push(remote);
});
});
bindListeners(self);
var u = opts.uri || opts.url;
if (u) self.navigate(u);
}
Driver.prototype = new EventEmitter;
Driver.prototype.appendTo = function (elem) {
return elem.appendChild(this.element);
};
Driver.prototype.navigate = function (uri, cb) {
this.element.setAttribute('src', uri);
if (typeof cb === 'function') {
// like .next() but skip the queue
this.once('open', function () {
});
}
};
Driver.prototype.next = function (cb) {
var q = this.queue;
if (q.remote.length) {
q.remote.shift().run(String(cb), this.vars);
}
else q.next.push(cb);
return this;
};
function bindListeners (self) {
var session, win;
bus.receiveMessage(function (ev) {
try {
var msg = json.parse(ev.data)
if (msg[0] === '__testling_open') {
session = create(self.element.contentWindow);
self.emit('open', msg[1]);
}
else if (session && msg[0] === '__testling_message') {
session.handle(msg[1]);
}
}
catch (err) {}
});
function create (win) {
var c = self.client.create();
c.on('request', function (req) {
bus.postMessage(
json.stringify([ '__testling_message', req ]),
'*',
win
);
});
c.start();
return c;
}
};