I am forced to append my widget outside of <body>. What are the side-effect of doing so?

元气小坏坏 提交于 2021-01-29 05:23:45

问题


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:

  1. Are there any side-effect of appending my widget outside of <body>?
  2. Is there any other solution to protect my widget from this code? (I can't use IFrame).
  3. If I were to use shadow-dom to 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!