-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiframeRPC.js
100 lines (75 loc) · 2.3 KB
/
iframeRPC.js
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
100
(function () {
function uuid4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
function addEvent( obj, type, fn )
{
if (obj.addEventListener)
obj.addEventListener( type, fn, false );
else if (obj.attachEvent)
{
obj["e"+type+fn] = fn;
obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
obj.attachEvent( "on"+type, obj[type+fn] );
}
}
window.iframeRPC = {
createClient : function(trustedParent, targetWindow) {
if (!targetWindow && window !== window.parent){
targetWindow = window.parent;
} else {
throw new Error('No Target Window Found');
}
var cbRegistry = {};
addEvent(window, "message", function receiveMessage(event) {
console.log('client event', event);
var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.origi
if (origin !== trustedParent) {
return;
}
var data = JSON.parse(event.data);
cbRegistry[data.uuid](data.result[0], data.result[1]);
delete cbRegistry[data.uuid];
}, false);
return function (service, input, cb) {
var uuid = uuid4();
console.log('sending to parent... maybe');
cbRegistry[uuid] = cb;
targetWindow.postMessage(
JSON.stringify({
'type': 'request',
'service': service,
'uuid': uuid,
'input': input,
}),
trustedParent
);
};
},
createService : function (services, trustedOrigin, targetFrame) {
addEvent(window, "message", function receiveMessage(event) {
console.log('service recieved event', event);
var data = JSON.parse(event.data);
if (!services[data.service]) {
return; // if its not a call to a valid service exit
}
var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
if (origin !== trustedOrigin) {
return;
}
services[data.service](data.input, function (err, res) {
console.log('sending back to child maybe');
targetFrame.postMessage(JSON.stringify({
type: 'response',
serviceHandler: data.service,
uuid: data.uuid,
result: [err, res]
}), '*');
});
}, false);
}
}
})();