If I want to run a Sitecore Personalize web experience (or web experiment) on a single page application, how can I achieve this?
1 Answer
This function can be used in Advanced Page Targeting to allow an experience to trigger on every virtual page load, rather than only on full page loads. It can be used along with other page targeting functions to trigger experiences after a delay or on hover over an element etc.
(function () {
targetingPassed();
var pushState = history.pushState;
history.pushState = function() {
pushState.apply(history, arguments);
targetingPassed();
};
})();
Example of on hover, Advanced Page Targeting functions:
// Triggers the experience when user moves their mouse over the specified HTML element
(function () {
const targetElementPath = "body"; // Edit here to change to target element
let targetElement;
function waitForElement() {
targetElement = document.querySelector(targetElementPath);
if (targetElement) {
console.log(targetElement);
targetElement.addEventListener("mouseover", triggerExperience);
}
else {
setTimeout(waitForElement, 100);
}
}
function triggerExperience() {
targetingPassed();
targetElement.removeEventListener("mouseover", triggerExperience);
}
waitForElement();
})();
For more page targeting examples see our GitHub repo: https://github.com/boxever/configurations/tree/master/Web%20Experiences/Page%20Targeting