使用客户端 JavaScript 监视添加到文档中的新元素

Using client javascript to monitor new elements added to document

本文关键字:新元素 元素 文档 客户端 JavaScript 监视 添加      更新时间:2023-09-26

几个月前我正在使用Object.observe()来监视来自window.document的任何递归更改。现在 O.o() 从 em6+ 中撤出,我需要自定义此行为。我需要访问文档中任何位置创建的新元素。

我尝试过这些项目(有效,但没有子递归):

https://github.com/MaxArt2501/object-observe

https://github.com/jdarling/Object.observe

https://github.com/jdarling/Object.observe

我从Mozilla MDN中阅读了使用proxy https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy 但我不确定使用哪个陷阱,或者如何使这个递归。

这是我与 O.o() 一起使用的确切代码:

                    var observer = new MutationObserver(function (mutations) {
                        mutations.forEach(function (mutation) {
                                console.log("Observed Mutation:");
                                //mutation.target
                                //mutation.type
                                //mutation.oldValue
                                //mutation.attributeName
                                //mutation.attributeNamespace
                                //mutation.removedNodes
                                //mutation.addedNodes
                        });
                    });
                    //mutation observer configuration
                    var config = {
                        childList: true,
                        attributes: true,
                        characterData: true,
                        subtree: true,
                        attributeOldValue: true,
                        characterDataOldValue: true
                        attributeFilter: false
                    };
                    // pass in the target node and options to mutation observer
                    observer.observe(document, config);
使用

或不使用 polyfill 访问新创建的对象所需的最少代码量是多少?

通过 irc.freenode.net ##javascript 找到了答案,来自: jaawerth

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver