Modify elements immediately after they are displayed (not after page completely loads) in greasemonkey script?

雨燕双飞 提交于 2019-12-02 00:20:29
  1. Make the script run at document-start by adding this code to script metablock:

    ..............
    // @run-at        document-start
    ..............
    // ==/UserScript==
    
  2. Now when the script runs there's nothing in the document so we'll attach the observer to the document root and will scan the added nodes for the container element .audience-info:

    var observer = new MutationObserver(function(mutations) {
        for (var i=0; i<mutations.length; i++) {
            var mutationAddedNodes = mutations[i].addedNodes;
            for (var j=0; j<mutationAddedNodes.length; j++) {
                var node = mutationAddedNodes[j];
                if (node.classList && node.classList.contains("audience-info")) {
                    node.firstElementChild.innerHTML = node.firstElementChild.innerHTML
                        .replace(/[\d.]+/g, function(m) { return 2 * m });
                    // don't hog resources any more as we've just done what we wanted
                    observer.disconnect();
                    return;
                }
            }
        }
    });
    observer.observe(document, {childList: true, subtree: true});
    

    When the observer is called the tooltips are already present in the document tree so you can simply move the code from "load" function into the observer before return without changing anything.

N.B. It's best to make the observer as fast as possible, particularly by using plain for-loops instead of function callbacks because of the overhead to call them, which might become an issue on a slow PC/device when opening a very complex page that generates thousands (quite a common case) or hundreds of thousands mutations (extremely rare but still!). And disconnect it once the job is done.

P.S. With setMutationHandler function the observer code would be:

// @require       https://greasyfork.org/scripts/12228/code/setMutationHandler.js
// ==/UserScript==

setMutationHandler(document, '.audience-info div:first-child', function(nodes) {
    this.disconnect();
    nodes.forEach(function(n) {
        n.innerHTML = n.innerHTML.replace(/[\d.]+/g, function(m) { return 2*m });
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!