// function helpers
function getSKU(target_sku) {
const SMB_URL = 'https://smb-api.makeupar.com/smb-api/query-product-summary.action?apiKey=SMB-Ojo6NDY4MjY=';
fetch(SMB_URL)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
let sku = data.skus.find(v => v.skuName == target_sku).skuNo;
console.log(sku);
getProductID(sku);
})
}
function getProductID(skuToFind) {
fetch('/products.json')
.then(function(response) {
return response.json();
})
.then(function(data) {
var variantId = null;
data.products.forEach(function(product) {
product.variants.forEach(function(variant) {
if (variant.sku === skuToFind) {
variantId = variant.id;
}
});
});
if (variantId) {
console.log('Variant ID:', variantId);
addToCart(variantId);
} else {
alert('SKU not found in Shopify Products');
}
})
.catch(function(error) {
console.error('Error:', error);
});
}
function addToCart(sku) {
var item = {
quantity: 1,
id: sku,
};
fetch('/cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(item),
})
.then(function(response) {
alert("Added to Cart!");
})
.then(function(data) {
// alert("Added to Cart!");
})
}
window.ymkAsyncInit = function () {
YMK.init();
YMK.addEventListener('loaded', function (e) {
var iframe = document.getElementById("YMK-module-iframe");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
var elementInIframe = iframeDocument.querySelector(".slick-track");
iframeDocument.querySelector("#Product").insertAdjacentHTML('afterend', `<div class='addtocart' data-sku="" data-name="" style='cursor:pointer;position:absolute;top:55px;right: 10px;background-color: #413354;padding: 15px;color: #fff;border-radius: 25px;font-size: 15px;'>Add To Cart</div>`);
iframeDocument.querySelector(".addtocart").addEventListener("click", (e) => {
getSKU(e.target.dataset.name);
});
const observer = new MutationObserver(callback);
function callback(mutationsList, observer) {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('this is a tset');
} else if (mutation.type === 'attributes') {
const data = iframeDocument.querySelector("#Product");
iframeDocument.querySelector(".addtocart").dataset.sku = data.querySelector('div[style*="font-weight: bold"]').textContent;
iframeDocument.querySelector(".addtocart").dataset.name = data.querySelector('div[style*="font-weight: normal"]').textContent;
}
}
}
const config = {
attributes: true,
childList: true,
subtree: true
};
observer.observe(elementInIframe, config);
})
}