');
const wrapper = new DOMParser().parseFromString(deviceBasedRender || personalization.rendered, "text/html");
const iframeSrcdoc = new DOMParser().parseFromString(wrapper.querySelector("iframe").getAttribute("srcdoc"), "text/html");
const newContent = new DOMParser().parseFromString(personalization.html, "text/html").querySelector(".bee-page-container");
const newStyle = new DOMParser().parseFromString(personalization.html, "text/html").querySelector("style");
// REPLACE DYNAMIC CONTENT
iframeSrcdoc.querySelector(".midway__showcase__content").replaceWith(newContent);
iframeSrcdoc.head.appendChild(newStyle);
// PROJECT CONFIG
if (window.MidwayPersonalization.projectCss) {
let style = document.createElement("style");
style.textContent = window.MidwayPersonalization.projectCss;
iframeSrcdoc.head.appendChild(style);
}
if (window.MidwayPersonalization.projectJs) {
let script = document.createElement("script");
script.textContent = window.MidwayPersonalization.projectJs;
document.head.appendChild(script);
}
wrapper.querySelector("iframe").setAttribute("srcdoc", iframeSrcdoc.documentElement.innerHTML);
wrapper.querySelector("iframe").setAttribute("id", Date.now());
const referenceElement = document.querySelectorAll(personalization.config.where.selector);
const alreadyRendered = document.querySelector(`[midway-personalization-id="${personalization.uuid}"]`);
if (!alreadyRendered) {
if (referenceElement.length) {
referenceElement.forEach((element, index) => {
if (index == personalization.config.where.occurrence - 1 || personalization.config.where.occurrence == "all") {
if (personalization.config.where.placement == "replace") {
element.innerHTML = wrapper.body.innerHTML;
} else {
element.insertAdjacentHTML(personalization.config.where.placement, wrapper.body.innerHTML);
}
}
});
} else {
window.MidwayPersonalization.notShownPersonalizations.push({
referenceElement: personalization.config.where.selector,
personalization: personalization
})
}
}
};
const renderCustom = (personalization) => {
const wrapper = new DOMParser().parseFromString(personalization.rendered, "text/html");
const dynamicContent = new DOMParser().parseFromString(personalization.html, "text/html").querySelector(".midway-dynamic-content");
if (dynamicContent) wrapper.querySelector(".midway-dynamic-content").replaceWith(dynamicContent);
const referenceElement = document.querySelectorAll(personalization.config.where.selector);
const alreadyRendered = document.querySelector(`[midway-personalization-id="${personalization.uuid}"]`);
if (!alreadyRendered) {
if (referenceElement.length) {
referenceElement.forEach((element, index) => {
if (index == personalization.config.where.occurrence - 1 || personalization.config.where.occurrence == "all") {
if (personalization.config.where.placement == "replace") {
element.innerHTML = wrapper.body.innerHTML;
} else {
element.insertAdjacentHTML(personalization.config.where.placement, wrapper.body.innerHTML);
}
}
});
} else {
window.MidwayPersonalization.notShownPersonalizations.push({
referenceElement: personalization.config.where.selector,
personalization: personalization
})
}
window.MidwayPersonalization.addJavascript(personalization.js);
}
};
//#endregion
//#region Event Handling
const turnOnEvents = (data) => {
data.personalizations.forEach((personalization) => {
addEventListeners(personalization.personalization_variant_id, personalization.config.builder[window.MidwayPersonalization.device]);
});
};
const addEventListeners = (id, config) => {
if (!id) return;
let personalizationElement = document.querySelector(`[midway-personalization-id="${id}"]`);
if (!personalizationElement) {
// addEventListeners(id, config);
}
if (personalizationElement) {
if (!window.MidwayPersonalization.isPreview) {
personalizationElement.addEventListener(
"click",
() => {
window.MidwayPersonalization.sendTrackingData({
personalization_variant_id: personalizationElement.getAttribute("midway-personalization-id"),
action: "personalization_click",
});
},
{ once: true }
);
}
personalizationElement.addEventListener("load", () => {
const doc = personalizationElement.contentDocument || personalizationElement.contentWindow.document;
const personalizationForm = doc.querySelector("form");
if (personalizationForm && config.type != 'custom') {
handleFormEvents(personalizationForm, config, id);
}
});
}
};
const handleFormEvents = (personalizationForm, config, id) => {
const button = personalizationForm.querySelector('button[type="submit"]');
const buttonCopy = personalizationForm.querySelector('button[type="submit"]');
const prevText = personalizationForm.querySelector('button[type="submit"]').textContent;
button.style.cursor = "pointer";
personalizationForm.setAttribute("onsubmit", "return false;");
personalizationForm.addEventListener(
"submit",
function (event) {
button.style.transitionProperty = "all";
button.style.transitionTimingFunction = "cubic-bezier(0.4, 0, 0.2, 1);";
button.style.transitionDuration = "300ms";
button.textContent = "Cargando...";
button.style = true;
button.style.backgroundColor = "#A2A2A2";
button.style.color = "#DADADA";
button.disabled = true;
event.preventDefault(); // Prevents the form from submitting normally
// Using FormData object
const formData = new FormData(this);
const data = {};
for (let pair of formData.entries()) {
data[pair[0]] = pair[1];
}
window.MidwayPersonalization.fetchTimeout(window.MidwayPersonalization.personalizationTrackEventEndpoint, {
timeout: window.MidwayPersonalization.timeout,
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
projectId: window.MidwayPersonalization.getProjectId(),
visitorId: window.MidwayPersonalization.getOrCreateVisitorId(),
url: window.MidwayPersonalization.currentUrl,
isMobile: window.MidwayPersonalization.isMobile(),
isDesktop: !window.MidwayPersonalization.isMobile(),
timeout: window.MidwayPersonalization.timeout,
timestamp: new Date().getTime(),
personalizationIds: [],
event: {
action: "personalization_submit",
personalization_variant_id: id,
data: { ...data },
},
applyRules: window.MidwayPersonalization.get("applyRules") == "true",
})
})
.then((data) => {
button.style = buttonCopy.style;
button.textContent = prevText;
button.disabled = false;
personalizationForm.insertAdjacentHTML("beforeend", `${config.formSubmittedText}
`);
if (config.formHideOnSubmit) {
setTimeout(() => {
window.MidwayPersonalization.close(id, config.outAnimation);
}, 2000);
}
})
.catch((error) => {
button.disabled = false;
log("[PERSONALIZATION] getPersonalization error: ", error);
});
},
{ once: true }
);
};
function monitorFormInputs(targets) {
const inputs = targets || document.querySelectorAll('input');
inputs.forEach(input => {
input.addEventListener('input', debounce(event => {
const inputValue = event.target.value;
if (isEmail(inputValue)) {
window.MidwayPersonalization.sendVisitorEmail(inputValue);
}
}, 500));
});
}
function observeDOMChanges() {
const targetNode = document.body;
const config = { childList: true, subtree: true };
const callback = function (mutationsList) {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
for (let node of mutation.addedNodes) {
if (node.nodeType === 1) {
const inputTargets = node.querySelectorAll('input')
if (inputTargets.length) monitorFormInputs(inputTargets)
let personalizationTargets = []
window.MidwayPersonalization.notShownPersonalizations.forEach(p => {
if (node.querySelectorAll(p.referenceElement).length) {
personalizationTargets.push(p.personalization)
}
})
if (personalizationTargets.length) renderNotShownPersonalizations(personalizationTargets)
}
}
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
}
const renderNotShownPersonalizations = (personalizationTargets) => {
personalizationTargets.forEach(target => {
showPersonalizationType(target)
})
}
//#endregion
//#region Push Notifications
const turnOnPushNotifications = (data) => {
// hidePush()
if (!data || window.MidwayPersonalization.reloaded) return;
var script = document.createElement("script");
script.src = "https://cdn.pn.vg/push/pushnews-launcher.js?appId=" + data.siteId + '&pnActivation=manual';
script.async = true;
document.body.appendChild(script);
};
const hidePush = () => {
const style = document.createElement('style');
style.innerHTML = 'div[data-smart-inject-id="OPTIN_HTML"] { display: none !important }';
document.head.appendChild(style);
}
window.MidwayPersonalization.handlePushNotificationSubscription = (event) => {
if (true === event.data.isSubscribed) {
var pushnewsId = event.data.pnId;
try {
navigator.sendBeacon(
window.MidwayPersonalization.personalizationTrackEventEndpoint,
JSON.stringify({
...window.MidwayPersonalization.buildRequestPayload(),
event: {
data: {
subscribe_push_id: pushnewsId,
}
},
})
);
} catch (error) {
log("[PERSONALIZATION] pushnewsNewSubscriptionHandler error: ", error);
}
}
};
//#endregion
//#region Scoped Functions
window.MidwayPersonalization.handleFormSubmission = async (personalization_id, data, handleSuccess = () => { }, handleError = () => { }) => {
await window.MidwayPersonalization.fetchTimeout(window.MidwayPersonalization.personalizationTrackEventEndpoint, {
timeout: window.MidwayPersonalization.timeout,
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
projectId: window.MidwayPersonalization.getProjectId(),
visitorId: window.MidwayPersonalization.getOrCreateVisitorId(),
url: window.MidwayPersonalization.currentUrl,
isMobile: window.MidwayPersonalization.isMobile(),
isDesktop: !window.MidwayPersonalization.isMobile(),
timeout: window.MidwayPersonalization.timeout,
timestamp: new Date().getTime(),
personalizationIds: [],
event: {
action: "personalization_submit",
personalization_variant_id: personalization_id,
data: { ...data },
},
applyRules: window.MidwayPersonalization.get("applyRules") == "true",
}),
})
.then((data) => {
handleSuccess(data);
})
.catch((error) => {
handleError(error);
});
};
window.MidwayPersonalization.loadIframe = (id) => {
var iFrameID = document.querySelector(`iframe[midway-personalization-id="${id}"]`);
if (iFrameID) {
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
}
};
window.MidwayPersonalization.iframeLoaded = (id, externalButton = false) => {
var personalizationIframe = document.querySelector(`iframe[midway-personalization-id="${id}"]`);
if (personalizationIframe) {
if (!window.MidwayPersonalization.isPreview) {
personalizationIframe.contentWindow.document.body.addEventListener(
"click",
(event) => {
window.MidwayPersonalization.sendTrackingData({
personalization_variant_id: personalizationIframe.getAttribute("midway-personalization-id"),
action: "personalization_click",
});
},
{ once: true }
);
}
personalizationIframe.height = "";
personalizationIframe.height = personalizationIframe.contentWindow.document.body.scrollHeight + "px";
personalizationIframe.style.maxHeight = "90vh";
const container = personalizationIframe.contentWindow.document.querySelector('.bee-popup-rows-container')
if (container) {
container.style.height = "100vh";
container.style.overflow = "auto";
}
if (externalButton) personalizationIframe.width = personalizationIframe.contentWindow.document.body.scrollWidth + "px";
}
};
window.MidwayPersonalization.iframeTriggerLoaded = (id) => {
var personalizationIframe = document.querySelector(`iframe[trigger="${id}"]`);
if (personalizationIframe) {
personalizationIframe.height = "";
personalizationIframe.height = personalizationIframe.contentWindow.document.body.scrollHeight + "px";
personalizationIframe.width = "";
personalizationIframe.width = personalizationIframe.contentWindow.document.body.scrollWidth + "px";
}
};
window.MidwayPersonalization.iframeLoadedButton = (id) => {
var personalizationIframe = document.querySelector(`iframe[midway-personalization-id-trigger="${id}"]`);
if (personalizationIframe) {
if (!window.MidwayPersonalization.isPreview) {
personalizationIframe.contentWindow.document.body.addEventListener(
"click",
(event) => {
window.MidwayPersonalization.sendTrackingData({
personalization_variant_id: personalizationIframe.getAttribute("midway-personalization-id-trigger"),
action: "personalization_click",
});
},
{ once: true }
);
}
personalizationIframe.height = "";
personalizationIframe.height = personalizationIframe.contentWindow.document.body.scrollHeight + "px";
personalizationIframe.width = "";
personalizationIframe.width = personalizationIframe.contentWindow.document.body.scrollWidth + "px";
}
};
window.MidwayPersonalization.open = (id, animation) => {
window.parent.document.body.style.overflow = "hidden";
const personalizationElement = document.querySelector(`[midway-personalization-wrapper-id="${id}"]`);
const backdrop = personalizationElement.querySelector(".backdrop");
const contentElement = personalizationElement.querySelector(".content");
if (backdrop) {
backdrop.classList.add = "animate__animated animate__fadeIn";
backdrop.style.display = "flex";
}
contentElement.style.visibility = "visible";
contentElement.classList.remove("animate__animated", animation);
void contentElement.offsetWidth;
contentElement.classList.add("animate__animated", animation)
const trigger = document.querySelector(`[midway-personalization-trigger-id="${id}"]`);
if (trigger) {
trigger.style.display = "none";
}
};
window.MidwayPersonalization.close = (id, animation, force = false) => {
window.parent.document.body.style.overflow = "auto";
const personalizationElement = document.querySelector(`[midway-personalization-wrapper-id="${id}"]`);
if (personalizationElement) {
if (force) {
personalizationElement.remove();
} else {
const backdrop = personalizationElement.querySelector(".backdrop");
const contentElement = personalizationElement.querySelector(".content");
const triggerButton = personalizationElement.querySelector(`[midway-personalization-trigger-id="${id}"]`);
if (animation == "none" || !animation) {
personalizationElement.style.display = "none";
} else {
if (animation == 'undefined') animation = 'animate__fadeOut';
if (backdrop) backdrop.className = "animate__animated animate__fadeOut";
if (contentElement) contentElement.className = "content animate__animated " + animation;
if (triggerButton) triggerButton.classList.add("animate__animated", animation);
setTimeout(() => {
personalizationElement.remove();
}, 1000);
}
}
}
};
window.MidwayPersonalization.get = (name) => {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var e = new RegExp("[\\?&]" + name + "=([^]*)").exec(location.search);
return null === e ? "" : decodeURIComponent(e[1].replace(/\+/g, " "));
};
window.MidwayPersonalization.fetchTimeout = async (resource, options = {}) => {
const { timeout = timeout } = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal,
});
clearTimeout(id);
return response;
};
window.MidwayPersonalization.getScrollPercent = () => {
let h = document.documentElement;
let b = document.body;
let st = "scrollTop";
let sh = "scrollHeight";
return ((h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight)) * 100;
};
window.MidwayPersonalization.addStylesheet = (string) => {
if (!string) return;
let style = document.createElement("style");
style.textContent = string;
document.head.appendChild(style);
};
window.MidwayPersonalization.addJavascript = (string) => {
if (!string) return;
let script = document.createElement("script");
script.textContent = string;
document.head.appendChild(script);
};
window.MidwayPersonalization.isMobile = () => {
let regexIsPhone =
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i;
let regexIsTablet =
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i;
let userAgent = navigator.userAgent || navigator.vendor || window.opera;
return regexIsPhone.test(userAgent) || regexIsTablet.test(userAgent.substr(0, 4));
};
window.MidwayPersonalization.sendTrackingData = (data) => {
try {
navigator.sendBeacon(
window.MidwayPersonalization.personalizationTrackEventEndpoint,
JSON.stringify({
...window.MidwayPersonalization.buildRequestPayload(),
event: {
...data,
},
})
);
} catch (error) {
log("[PERSONALIZATION] sendTrackingData error: ", error);
}
};
window.MidwayPersonalization.buildRequestPayload = (addSku = false) => {
const urlParams = new URLSearchParams(window.location.search);
return {
...(searchForSKU() && addSku && { sku: searchForSKU() }),
projectId: window.MidwayPersonalization.getProjectId(),
visitorId: window.MidwayPersonalization.getOrCreateVisitorId(),
url: typeof MidwayPlatform !== 'undefined' ? (MidwayPlatform == 'shopify' ? window.MidwayPersonalization.currentUrl.replace(/\/wpm.*\/modern/, '') : window.MidwayPersonalization.currentUrl) : window.MidwayPersonalization.currentUrl,
isMobile: window.MidwayPersonalization.isMobile() ? 1 : 0,
isDesktop: !window.MidwayPersonalization.isMobile() ? 1 : 0,
timeout: window.MidwayPersonalization.timeout,
timestamp: new Date().getTime(),
personalizationIds: urlParams.get("previewId") ? parsePreviewIds() : "",
applyRules: (urlParams.get("applyRules") == "true" ? 1 : 0) || 0,
};
};
window.MidwayPersonalization.getProjectId = () => {
return MidwayProjectId ?? null;
};
window.MidwayPersonalization.getOrCreateVisitorId = () => {
let visitorId = window.MidwayPersonalization.getCookie("visitorId");
if (!visitorId) {
visitorId = window.MidwayPersonalization.generateVisitorId();
window.MidwayPersonalization.setCookie("visitorId", visitorId, 365);
}
return visitorId;
};
window.MidwayPersonalization.generateVisitorId = () => {
const uniquePart = new Date().getTime().toString(36);
const randomPart = Math.random().toString(36).substring(2, 10);
return "mid_" + uniquePart + randomPart;
};
window.MidwayPersonalization.setCookie = (name, value, daysToExpire) => {
const date = new Date();
date.setTime(date.getTime() + daysToExpire * 24 * 60 * 60 * 1000);
const expires = "expires=" + date.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
};
window.MidwayPersonalization.getCookie = (name) => {
const cookieName = name + "=";
const cookies = document.cookie.split(";");
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
if (cookie.indexOf(cookieName) === 0) {
return cookie.substring(cookieName.length, cookie.length);
}
}
return null;
};
window.MidwayPersonalization.addAlpha = (color, opacity) => {
var _opacity = Math.round(Math.min(Math.max(opacity || 1, 0), 1) * 255);
return color + _opacity.toString(16).toUpperCase();
};
window.MidwayPersonalization.reload = () => { }
window.MidwayPersonalization.refresh = () => {
window.MidwayPersonalization.personalizationsImmediate.forEach((p) => {
window.MidwayPersonalization.close(p.personalization_variant_id, null, true);
});
window.MidwayPersonalization.personalizationsExit.forEach((p) => {
window.MidwayPersonalization.close(p.personalization_variant_id, null, true);
});
window.MidwayPersonalization.personalizationsTimer.forEach((p) => {
window.MidwayPersonalization.close(p.personalization_variant_id, null, true);
});
window.MidwayPersonalization.personalizationsScroll.forEach((p) => {
window.MidwayPersonalization.close(p.personalization_variant_id, null, true);
});
window.MidwayPersonalization = {
...window.MidwayPersonalization,
device: window.innerWidth < 768 || screen.width < 768 ? "mobile" : "desktop",
// Endpoints
personalizationEndpoint: "https://" + MidwayUrl + "/api/2.0/personalizations",
personalizationTrackEventEndpoint: "https://" + MidwayUrl + "/api/2.0/tracking/project",
// Styles & Javascripts
systemStylesPlaced: false,
systemJavascriptPlaced: false,
projectStylesPlaced: false,
projectJavascriptPlaced: false,
// Personalizations
personalizationsImmediate: [],
personalizationsExit: [],
personalizationsTimer: [],
personalizationsScroll: [],
// Custom data
customData: {},
isPreview: false,
// Referrer
currentUrl: window.location.href,
// Carousel plugin
carouselPluginLoaded: false,
// Counting the seconds passed on the website.
secondsPassed: 0,
// Setting a default timeout to the personalization request, the user can modify this in the installation script.
languageAutodetect: typeof setLanguageAutodetect === "boolean" ? setLanguageAutodetect : true,
// Setting a default timeout to the personalization request, the user can modify this in the installation script.
timeout: typeof MidwayTimeout === "number" ? MidwayTimeout : 5000,
// Setting a default animation to the personalization, the user can modify this in the installation script.
animation: typeof setAnimation === "boolean" ? setAnimation : true,
// Setting a default log level to analyse what is happening, the user can modify this in the installation script (debug, info, critical).
logLevel: typeof setLogLevel === "string" ? setLogLevel : "none",
logLevelNumber: {
none: 0,
debug: 1,
info: 2,
critical: 3,
},
// Languages
language: "en",
production: false,
notShownPersonalizations: [],
};
initialize()
}
//#endregion
//#region Helpers
const parsePreviewIds = () => {
const urlParams = new URLSearchParams(window.location.search);
const previewIds = urlParams.get("previewId");
return "" + previewIds.replace("/", "")
}
const isPreviewMode = () => {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get("previewId");
};
const isProductionMode = (data) => {
return Boolean(data?.project_setting?.personalization_production);
};
const isBrowserMode = () => {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get("showPersonalizations") == "true" || localStorage.getItem("showPersonalizations");
};
const enableBrowserMode = () => {
localStorage.setItem("showPersonalizations", "true");
};
const disableBrowserMode = () => {
localStorage.removeItem("showPersonalizations");
};
const filterBeeCSS = (css, display) => {
try {
if (display == "desktop") {
const regex = /@media\s*\(max-width:\s*\d+px\)/;
const modifiedCss = css.replace(regex, "@media (min-width:99999px)");
return modifiedCss;
} else {
const regex = /@media\s*\(max-width:\s*520px\)/g;
const regex2 = /max-width:\s*250px/g;
const modifiedCss = css.replace(regex, "@media (min-width:0px)").replace(regex2, "max-width:10000px;")
return modifiedCss;
}
} catch (error) {
log(error);
}
};
const insertTestBadge = () => {
const badge = document.createElement("div");
badge.style.width = "100%";
badge.style.padding = "5px 10px";
badge.style.backgroundColor = "#242422";
badge.style.color = "#e6e2d8";
badge.style.fontSize = "12px";
badge.style.zIndex = "9999";
badge.style.fontWeight = "bold";
badge.style.display = "flex";
badge.style.flexDirection = "row";
badge.style.alignItems = "center";
badge.style.justifyContent = "space-between";
const img = document.createElement("img");
img.src = "https://midway.la/wp-content/uploads/2024/04/logo-horizontal-blanco-4-300px.png";
img.style.verticalAlign = "middle";
img.style.width = "80px";
document.body.insertAdjacentHTML(
"afterbegin",
`
`
);
};
const searchForSKU = () => {
// VTEX
if (typeof MidwaySearchVtexSKU !== 'undefined' && MidwaySearchVtexSKU) {
let mightBeSKU = document.querySelector('meta[property="product:sku"]');
if (mightBeSKU) {
return mightBeSKU.getAttribute("content");
}
}
// WOOCOMMERCE
mightBeSKU = document.querySelector('a[data-product_sku="product:sku"]');
if (mightBeSKU) {
return mightBeSKU;
}
// PRESTASHOP
mightBeSKU = document.querySelector('div[id="product-details"]');
if (mightBeSKU) {
const data = JSON.parse(mightBeSKU.getAttribute("data-product"));
return data.reference;
}
return false;
};
function debounce(func, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
function isEmail(input) {
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
return emailPattern.test(input);
}
//#endregion
//#region Load Scripts
const loadAnimateCSS = () => {
let animate = document.createElement("link");
animate.rel = "stylesheet";
animate.type = "text/css";
animate.href = "https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css";
document.getElementsByTagName("HEAD")[0].appendChild(animate);
};
const loadTinySlider = () => {
let tiny = document.createElement("link");
tiny.rel = "stylesheet";
tiny.type = "text/css";
tiny.href = "https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.4/tiny-slider.css";
document.getElementsByTagName("HEAD")[0].appendChild(tiny);
let script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://cdnjs.cloudflare.com/ajax/libs/tiny-slider/2.9.2/min/tiny-slider.js";
document.head.appendChild(script);
};
const loadFontAwesome = () => {
let fa = document.createElement("link");
fa.rel = "stylesheet";
fa.type = "text/css";
fa.href = "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.2/css/fontawesome.min.css";
fa.integrity = "sha384-BY+fdrpOd3gfeRvTSMT+VUZmA728cfF9Z2G42xpaRkUGu2i3DyzpTURDo5A6CaLK";
fa.crossOrigin = "anonymous";
document.getElementsByTagName("HEAD")[0].appendChild(fa);
};
//#endregion
//#region Component Selector
const enableComponentSelector = () => {
let selected = null;
document.body.insertAdjacentHTML(
"afterend",
`
Pasa el mouse por arriba de un elemento
`
);
document.addEventListener('mouseover', (event) => {
const target = event.target;
// Evitamos duplicar el pseudo-elemento
if (target.dataset.highlighted) return;
// Marcamos el elemento como resaltado
target.dataset.highlighted = true;
// Añadimos posición relativa para que el pseudo-elemento se coloque correctamente
const computedStyle = window.getComputedStyle(target);
if (computedStyle.position === 'static') {
target.style.position = 'relative';
}
// Creamos el pseudo-elemento dinámico
const highlight = document.createElement('div');
highlight.className = 'highlight-effect';
Object.assign(highlight.style, {
position: 'absolute',
top: '-5px',
left: '-5px',
right: '-5px',
bottom: '-5px',
border: '2px solid rgba(0, 0, 255, 0.8)',
borderRadius: computedStyle.borderRadius, // Copiamos el radio de borde si existe
pointerEvents: 'none',
zIndex: 9999,
});
// Añadimos el pseudo-elemento al contenedor
target.appendChild(highlight);
target.addEventListener(
"click",
(x) => {
x.preventDefault();
selected = getFullSelector(x.target);
document.getElementById("selectorBar").innerHTML = selected;
window.opener.postMessage(selected, "*");
window.close();
},
{ once: true }
);
});
document.addEventListener('mouseout', (event) => {
const target = event.target;
// Eliminamos el efecto y limpiamos la marca
const highlight = target.querySelector('.highlight-effect');
if (highlight) highlight.remove();
delete target.dataset.highlighted;
});
window.addEventListener("beforeunload", function (e) {
this.window.opener.getInfo(selected);
});
};
function getFullSelector(e) {
var s = "",
t,
i,
c,
p,
n;
do {
t = e.tagName.toLowerCase();
i = e.hasAttribute("id") ? "#" + e.id : "";
c = e.hasAttribute("class") ? "." + e.className.split(/\s+/).join(".") : "";
p = e.parentNode;
n =
Array.prototype.filter
.call(e.parentNode.childNodes, function (x) {
return x.nodeType == Node.ELEMENT_NODE;
})
.indexOf(e) + 1;
s = t + i + c + ":nth-child(" + n + ") > " + s;
} while (!p || !(e = p).tagName.match(/^HTML$/i));
return s.slice(0, -3);
}
//#endregion
//#region Debugger
const startDebugger = (rawData) => {
localStorage.setItem("midwayDebugger", true);
fetch("https://" + MidwayUrl + "/tracking/debugger.html", {
method: 'GET',
})
.then(response => {
if (!response.ok) {
throw new Error('[MIDWAY DEBUGGER] Error');
}
return response.text();
})
.then(data => {
window.MidwayPersonalization.debuggerData = rawData;
let tailwindScript = document.createElement("script");
tailwindScript.type = "text/javascript";
tailwindScript.src = "https://cdn.tailwindcss.com";
document.head.appendChild(tailwindScript);
let iconScript = document.createElement("script");
iconScript.type = "text/javascript";
iconScript.src = "https://code.iconify.design/3/3.1.0/iconify.min.js";
document.head.appendChild(iconScript);
document.body.insertAdjacentHTML("afterend", data);
if (!document.querySelector(`script[src="https://${MidwayUrl}/tracking/debugger.js"]`)) {
tailwindScript.onload = () => {
let debuggerScript = document.createElement("script");
debuggerScript.type = "text/javascript";
debuggerScript.src = "https://" + MidwayUrl + "/tracking/debugger.js";
document.head.appendChild(debuggerScript);
debuggerScript.onload = () => {
replaceData();
}
}
} else {
const footer = document.getElementById("mwd-footer");
const backdrop = document.getElementById("mwd-backdrop");
const modal = document.getElementById("mwd-modal");
footer.remove()
backdrop.remove()
modal.remove()
replaceData();
}
})
.catch(error => {
console.error('Error:', error);
});
}
//#endregion
//#region Watch URL changes
const watchForURLChanges = () => {
if (!window.MidwayPersonalization.urlChangeListenerSet) {
window.MidwayPersonalization.urlChangeListenerSet = true
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;
history.pushState = function (...args) {
if (location.pathname != args[2]) {
window.dispatchEvent(new Event('urlchange'));
}
originalPushState.apply(this, args);
};
history.replaceState = function (...args) {
if (location.pathname != args[2]) {
window.dispatchEvent(new Event('urlchange'));
}
originalReplaceState.apply(this, args);
};
window.addEventListener('urlchange', function () {
interceptDataLayer()
});
window.addEventListener('popstate', function () {
interceptDataLayer()
});
}
}
const interceptDataLayer = () => {
const originalPush = dataLayer.push;
dataLayer.push = function () {
if (dataLayer.find(item => item.event == "midway.load")) {
if (["pageView", "page_view"].includes(arguments[0].event)) {
dataLayer.push = originalPush;
window.MidwayPersonalization.refresh();
}
}
const result = originalPush.apply(this, arguments);
return result;
};
}
const addMidwayToDataLayer = () => {
dataLayer.push({
"event": "midway.load",
})
}
//#endregion
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get("midwayQuerySelector")) {
enableComponentSelector();
} else {
initialize();
if (typeof dataLayer !== "undefined" && Array.isArray(dataLayer)) {
if (dataLayer.every(item => item.event != "midway.load")) {
addMidwayToDataLayer()
watchForURLChanges()
}
}
}
// #region Logging
function log(...args) {
const urlParams = new URLSearchParams(window.location.search);
const enableLogs = urlParams.has("midwayLogs") && urlParams.get("midwayLogs") === "true";
if (enableLogs) {
console.log(...args);
}
}
//#endregion
}