-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
34 lines (32 loc) · 1.04 KB
/
script.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
(async function() {
const addToCart = skus =>
fetch(`/wp-json/konfig/add-to-cart`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ skus: skus })
});
const iframeMessage = async event => {
if (!event || !Array.isArray(event.data)) return;
const [action, skus = []] = event.data;
switch (action) {
case "ADD_TO_CART": {
try {
const products = await addToCart(skus);
const elements = document.getElementsByClassName("konfig");
const redirectUrl =
elements && elements[0].getAttribute("data-redirect");
if (redirectUrl) window.location.assign(redirectUrl);
window.parent.postMessage(["ADD_TO_CART_SUCCESS", skus], "*");
} catch (err) {
console.warn("error", err);
window.parent.postMessage(["ADD_TO_CART_ERROR", err], "*");
}
}
default:
console.log(action);
}
};
window.addEventListener("message", iframeMessage, false);
})();