@funnelenvy-npm/fe-dev-utils
Version:
Helper function to build client side A/B tests
52 lines (51 loc) • 2.44 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const on_error_1 = __importDefault(require("../on-error"));
const onUrlChange = ({ callback, activity, errorHandler, }) => {
if (typeof callback !== 'function') {
throw new Error('Callback function must be provided');
}
const mutationConfig = { childList: true, subtree: true };
// Create a new MutationObserver instance to observe changes to the document body
const observer = new MutationObserver((mutationsList) => {
mutationsList.forEach((mutation) => {
// Store the current URL in a separate variable to make the code more concise
const currentUrl = window.location.href;
// Check if the URL has changed since the last observation
if (observer.previousUrl !== currentUrl) {
const oldHref = observer.previousUrl;
// Update the previous URL and execute the callback function
observer.previousUrl = currentUrl;
// console.log('URL changed!');
observer.disconnect(); // Disconnect the observer to avoid triggering an infinite loop when making DOM changes in the callback function
try {
callback(oldHref, mutation);
}
catch (error) {
console.log(`Error in callback function: ${error}`);
}
observer.observe(document.documentElement, mutationConfig); // Reconnect the observer to continue observing URL changes
}
});
});
// Initialize the previous URL to the current URL
try {
observer.previousUrl = window.location.href;
// Start observing changes to the document documentElement to detect URL changes
observer.observe(document.documentElement, mutationConfig);
}
catch (err) {
// Validate that `err` is an Error or convert it to an Error
const error = err instanceof Error ? err : new Error('Unknown error occurred');
if (errorHandler && typeof errorHandler === 'function') {
errorHandler({ activity, error });
}
else {
(0, on_error_1.default)({ activity, error });
}
}
};
exports.default = onUrlChange;