V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MCorMC
V2EX  ›  程序员

动态加载的页面要怎么样用外部脚本修改内容?

  •  
  •   MCorMC · 2022-05-26 11:11:47 +08:00 · 942 次点击
    这是一个创建于 707 天前的主题,其中的信息可能已经有所发展或是发生改变。

    onload 的时候很多东西还没加载出来,直接执行达不到我需要的效果,js 只会一些基础的东西,对这种情况没什么好的思路,我现在的做法是用 setinterval 每一秒检查一次需要的东西有没有加载出来,但这样感觉效率好低,有更好的办法吗

    3 条回复    2022-05-26 11:32:15 +08:00
    iPc666
        1
    iPc666  
       2022-05-26 11:17:56 +08:00
    用 MutationObserver ,把

    ```js
    const eleObserver = new MutationObserver((ele) => {
    //判断 ele 里有你要的元素
    //然后执行操作
    });
    eleObserver.observe(document.body, {childList: true, subtree: true});
    ```
    wdssmq
        2
    wdssmq  
       2022-05-26 11:26:00 +08:00
    // 元素变化监听
    const fnElChange = (el, fn = () => { }) => {
    const observer = new MutationObserver((mutationRecord, mutationObserver) => {
    // _log('body attributes changed!!!'); // body attributes changed!!!
    // _log('mutationRecord = ', mutationRecord); // [MutationRecord]
    // _log('mutationObserver === observer', mutationObserver === observer); // true
    fn(mutationRecord, mutationObserver);
    mutationObserver.disconnect(); // 取消监听,正常应该在回调函数中根据条件决定是否取消
    });
    observer.observe(el, {
    // attributes: false,
    // attributeFilter: ["class"],
    childList: true,
    // characterData: false,
    subtree: true,
    });
    };

    可以封装一下;

    wdssmq/userscript: 各种猴子脚本
    https://github.com/wdssmq/userscript
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2188 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 11:18 · PVG 19:18 · LAX 04:18 · JFK 07:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.