You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TamperMonkey脚本无法检测leleplayer-bar元素的问题求助

问题排查:TamperMonkey脚本无法检测到动态加载元素

问题描述

要隐藏网页中点击粉色按钮后动态加载的视频进度条(类名leleplayer-bar),核心代码document.getElementsByClassName("leleplayer-bar")[0].hidden = true在Chrome开发者控制台中可正常执行,但作为TamperMonkey用户脚本运行时,控制台持续输出“Target element not found.”,无法定位目标元素。

原因分析

  1. 匹配规则过于宽泛:原脚本@match */*/*会匹配所有页面,不仅在目标页面运行,也会在其他页面执行,导致日志混乱,同时可能在目标页面的执行优先级或上下文出现问题。
  2. 运行时机过早:@run-at document-start会在文档尚未开始解析时执行脚本,此时document.body还未生成,MutationObserver无法正确绑定到目标节点。
  3. 目标元素可能在iframe内部:视频播放器通常会被嵌入到iframe中,直接在主文档上下文查找元素会失败,而控制台执行时可能是切换到了iframe的上下文。

修复方案

  1. 精准匹配目标页面:将@match规则修改为只匹配目标网站的播放页面,避免不必要的执行。
  2. 调整脚本运行时机:将@run-at设置为document-body,确保document.body已存在后再初始化监听逻辑。
  3. 添加iframe检测逻辑:遍历页面中的iframe,进入iframe上下文查找目标元素,并为iframe绑定DOM变化监听。

修复后的完整代码

// ==UserScript==
// @name         Hide leleplayer-bar
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  Hides elements with class leleplayer-bar, including those in iframes
// @author       Your name
// @match        https://www.dmla5.com/play/*
// @grant        none
// @run-at       document-body
// ==/UserScript==

(function() {
    function hideElement(targetDoc) {
        const elementsToHide = targetDoc.getElementsByClassName("leleplayer-bar");
        if (elementsToHide.length > 0) {
            elementsToHide[0].hidden = true;
            console.log("Target element hidden successfully.");
            return true;
        }
        return false;
    }

    function setupObserver(targetDoc) {
        const targetNode = targetDoc.body;
        if (!targetNode) return;

        const config = { childList: true, subtree: true };
        const observer = new MutationObserver((mutationsList, obs) => {
            for (const mutation of mutationsList) {
                if (mutation.type === 'childList' && hideElement(targetDoc)) {
                    obs.disconnect();
                    return;
                }
            }
        });
        observer.observe(targetNode, config);
    }

    // 处理主文档
    if (hideElement(document)) return;
    setupObserver(document);

    // 处理页面中的iframe
    const checkIframes = () => {
        const iframes = document.getElementsByTagName('iframe');
        for (const iframe of iframes) {
            try {
                const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                if (hideElement(iframeDoc)) continue;
                setupObserver(iframeDoc);
            } catch (e) {
                // 跨域iframe无法访问,跳过
                continue;
            }
        }
    };

    // 初始检查iframe,同时监听iframe的添加
    checkIframes();
    const iframeObserver = new MutationObserver((mutationsList) => {
        for (const mutation of mutationsList) {
            if (mutation.type === 'childList') {
                mutation.addedNodes.forEach(node => {
                    if (node.tagName === 'IFRAME') {
                        setTimeout(() => checkIframes(), 500);
                    }
                });
            }
        }
    });
    iframeObserver.observe(document.body, { childList: true, subtree: true });
})();

内容的提问来源于stack exchange,提问作者Electron X

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 12:53:10