-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhelper.js
85 lines (75 loc) · 2.35 KB
/
helper.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
class Helper {
popupRef;
popupUrl;
popupName;
constructor({ url, name }) {
// assign a name to this popup window, the JVS will send this value back in the response as an additional
// security measure that this calling application should validate
this.popupName = name;
this.popupUrl = new URL(url);
// tells the JVS which mode to use, currently the UI supports a popup mode only
this.popupUrl.searchParams.set("mode", encodeURIComponent("popup"));
// tells the JVS which origin should receive the response, for non local development this value should
// exist in the ALLOWLIST for the JVS UI instance you are running
this.popupUrl.searchParams.set(
"origin",
encodeURIComponent(window.location.origin)
);
}
// receiveMessage validates the validity of the popup response origin and returns the token
#receiveMessage = (event) => {
// only trust the origin we opened
console.log(`${event.origin} == ${this.popupUrl.origin}`)
if (event.origin !== this.popupUrl.origin) {
throw new Error("invalid popup origin");
}
// parse the response data
const data = JSON.parse(event.data);
// only trust valid source variable
if (data.source !== this.popupName) {
throw new Error("invalid popup source");
}
return data.payload
};
// requestToken checks for a existing listeners and handles the response from the JVS UI
requestToken = () => {
return new Promise((resolve, reject) => {
//remove existing event listener
window.removeEventListener(
"message",
(event) => {
try {
resolve(this.#receiveMessage(event));
} catch (err) {
reject(err);
}
},
false
);
// popup never created or was closed
if (!this.popupRef || this.popupRef.closed) {
this.popupRef = window.open(
this.popupUrl.toString(),
this.popupName,
"popup=true,width=500,height=600"
);
}
// popup exists, show it
else {
this.popupRef.focus();
}
// listen for response
window.addEventListener(
"message",
(event) => {
try {
resolve(this.#receiveMessage(event));
} catch (err) {
reject(err);
}
},
false
);
});
};
}