Last active
March 26, 2021 08:20
-
-
Save dmjcomdem/4d2e592ae3f23f60ab40d508773d16c3 to your computer and use it in GitHub Desktop.
MutationObserver for addserver-tag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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