首页 > 解决方案 > MutationObserver 不断循环遍历每个项目并在 TamperMonkey 脚本中创建冗余按钮

问题描述

我正在编写一个与 Tampermonkey 一起使用的脚本,它几乎完成了,但我一直遇到一个问题,mutationobserver 循环遍历页面上的每个指定项目。该页面将具有不同数量的“输入货币组”项目,每次加载脚本时,我都需要它在看到加载输入框时向页面添加按钮。

但是,不是一次添加按钮,而是为查找该框的每次迭代添加按钮,因此我需要将其限制为仅运行一次该内部函数。这是代码。

const isAddPage = window.location.hash === '#/p=add' || window.location.hash === '#/add',
        {
            loader,
            popup,
            buttons,
            getCurrentTab
        } = pricer;

const observer = new MutationObserver((mutations) => {
        for (const mutation of mutations) {
            for (const node of mutation.addedNodes) {
                if (node.classList && node.classList.contains('input-money-group')) {

                    console.log('its working');
                    // Create all elements & update tab.
                    if (isAddPage) {
                        setTimeout(function() {
                            getCurrentTab();
                            loader.build();
                            popup.build();
                            buttons.build();
                            observer.disconnect();
                        }, 250);
                      }

                }
            }
        }
    })

    const wrapper = document.querySelector('#bazaarroot')
    observer.observe(wrapper, {
        subtree: true,
        childList: true })

我已经尝试过使用observer.disconnect(); 在不同的地方,它不会阻止它创建冗余按钮。

标签: javascriptjavatampermonkeymutation-observersmutation

解决方案


推荐阅读