Skip to content

Instantly share code, notes, and snippets.

@NickFoden
Created April 7, 2025 12:19
Show Gist options
  • Save NickFoden/cf10e8d365938a4076f2b0a33d64c268 to your computer and use it in GitHub Desktop.
Save NickFoden/cf10e8d365938a4076f2b0a33d64c268 to your computer and use it in GitHub Desktop.
How to Copy window.dataLayer
const getCircularReplacer = () => {
const seen = new WeakSet(); // Use WeakSet to avoid memory leaks by holding strong references
return (key, value) => {
// If the value is an object or array, check if we've seen it
if (typeof value === 'object' && value !== null) {
// Check if it's a DOM element (a very common cause of circularity)
if (value instanceof Element) {
// Represent the DOM element simply, e.g., by its tag, id, and classes
let representation = `[DOM Element: ${value.tagName}`;
if (value.id) representation += `#${value.id}`;
if (value.className && typeof value.className === 'string') representation += `.${value.className.split(' ').join('.')}`;
representation += ']';
return representation; // Return the simple representation instead of the complex object
}
// Check if we've encountered this object before (circular reference)
if (seen.has(value)) {
return '[Circular Reference]'; // Replace circular reference with a placeholder string
}
// If it's a new object, add it to our set
seen.add(value);
}
// Return the value unchanged if it's not a circular reference or DOM element
return value;
};
};
// Now use this replacer with JSON.stringify and copy
copy(JSON.stringify(window.dataLayer, getCircularReplacer(), 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment