How to run a selector on a dynamically generated page?

后端 未结 2 402
既然无缘
既然无缘 2021-01-26 00:51

I have a selector which works in GM_addStyle but not in jQuery. I want to use jQuery :contains() which is not available in CSS3.

But, it appear

相关标签:
2条回答
  • 2021-01-26 01:31

    Waiting for the element:

    function waitForElement(id, callback, timeout){
        if('undefined' == typeof timeout) timeout = 30;
        timeout = timeout * 1000;
        var time = 0;
        var poops = setInterval(function(){
            if(time >= timeout) clearInterval(poops);
            if(document.getElementById(id)){
                clearInterval(poops);
                callback();
            }
            time += 100;
        }, 100);
    }
    

    One way to include jQuery:

    (function(callback) {
      var script = document.createElement("script");
      script.setAttribute("src", "//code.jquery.com/jquery-1.11.3.min.js");
      script.addEventListener('load', callback);
      document.body.appendChild(script);
    })
    
    // main codez go in here
    (function(){
      window.alert($('a').length+" Links");
    });
    
    0 讨论(0)
  • 2021-01-26 01:51

    Sometimes you can wait for the window load event, but in general, you must use AJAX-aware techniques. See Fire Greasemonkey script on AJAX request.

    So, using waitForKeyElements(), a complete Tampermonkey script would be like:

    // ==UserScript==
    // @name     _Use jQuery on AJAXed content
    // @match    http://YOUR_SERVER.COM/YOUR_PATH/*
    // @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant    GM_addStyle
    // ==/UserScript==
    //- The @grant directive is needed to restore the proper sandbox.
    
    waitForKeyElements (
        "#T301444200 > tbody > tr.SelPrimary > td:nth-child(1) > nobr > span", styleNode
    );
    
    function styleNode (jNode) {
        jNode.css ("color", "blue");
    }
    

    Note that .css("color","blue","important"); is not valid jQuery and is probably not needed in this case.

    If this is one of the rare sites where you do need !important, use:

    jNode[0].style.setProperty ("color", "blue", "important");
    

    Inside styleNode(), above.

    0 讨论(0)
提交回复
热议问题