问题
I am in a strange situation. I am a widget developer and one of my client is using my widget (written in svelte) on their website.
Unfortunately their website, written in wordpress has some strange MutationObserver code in it. The callback of MutationObserver actually messes up with my widget when any DOM nodes are changed. Following is the culprit code (comes from a plugin called twemoji):
const cb = function (records) {
for (var addedNodes, removedNodes, length, a, r = records.length; r--;) {
if (addedNodes = records[r].addedNodes, removedNodes = records[r].removedNodes, 1 === (length = addedNodes.length) && 1 === removedNodes.length && 3 === addedNodes[0].nodeType && "IMG" === removedNodes[0].nodeName && addedNodes[0].data === removedNodes[0].alt && "load-failed" === removedNodes[0].getAttribute("data-error")) return;
for (; length--;) {
if (3 === (a = addedNodes[length]).nodeType) {
if (!a.parentNode) continue;
for (; a.nextSibling && 3 === a.nextSibling.nodeType;) {
//******** culprit code ********
a.nodeValue = a.nodeValue + a.nextSibling.nodeValue, a.parentNode.removeChild(a.nextSibling)
}
a = a.parentNode
}
}
}
};
const x = new MutationObserver(cb).observe(document.body, {childList: !0, subtree: !0}), f(document.body)
Since above code is observing entire body, to avoid this code my widget.js should append my widget outside of the <body> like this.
<head>
<script src="path-to-my/widget.js"></script>
</head>
<body>
<body>
<div id="my-widget"></div>
My question is:
- Are there any side-effect of appending my widget outside of
<body>? - Is there any other solution to protect my widget from this code? (I can't use
IFrame). - If I were to use
shadow-domto encapulate my widget, would it solve the problem?
来源:https://stackoverflow.com/questions/65783759/i-am-forced-to-append-my-widget-outside-of-body-what-are-the-side-effect-of-d