Skip to content

Instantly share code, notes, and snippets.

@dmjcomdem
Last active March 26, 2021 08:20
Show Gist options
  • Save dmjcomdem/4d2e592ae3f23f60ab40d508773d16c3 to your computer and use it in GitHub Desktop.
Save dmjcomdem/4d2e592ae3f23f60ab40d508773d16c3 to your computer and use it in GitHub Desktop.
MutationObserver for addserver-tag
// prettier-ignore
(function() {
function mutationObserver(
node,
callback,
options = {
childList: true,
subtree: true,
attributes: true,
attributeOldValue: false,
characterDataOldValue: false
}
) {
const observer = new MutationObserver(function([mutation]) {
callback(mutation);
});
observer.observe(node, options);
return observer.disconnect;
}
console.log(mutationObserver)
function resizeHandler(node) {
const height = node.firstChild.contentDocument.body.firstChild.offsetHeight;
node.style.width = '100%';
node.style.height = height + 'px';
}
function autoResizeIframe(wrapperIframe) {
mutationObserver(wrapperIframe, function(mutation) {
resizeHandler(mutation.target)
window.addEventListener('resize', () => resizeHandler(mutation.target));
});
}
mutationObserver(document.body, function(mutation) {
if (mutation.target.tagName === 'IAE-TAG') {
const iframe = mutation.addedNodes[0];
if (iframe instanceof HTMLIFrameElement) {
autoResizeIframe(mutation.target);
console.log(iframe);
window.addEventListener('message', e => {
if (e.data && e.data.startsWith('adserver-content')) {
const data = JSON.parse(e.data.replace(/^adserver-content/g, ''));
if (data.event === 'addToBasket') {
setTimeout(() => {
const result = { event: 'addToBasket', message: 'Отправленно в Iframe' };
iframe.contentWindow.postMessage('adserver-content' + JSON.stringify(result),'*');
}, 2000);
}
}
});
}
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment