0

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 appears that the id does not exist on my page when I view source but it's dynamically generated.
How do I tell Tampermonkey to run JS after the whole page loads?

I have tried different JS @run-at settings but no luck.

//works
GM_addStyle(" \
   #T301444200 > tbody > tr.SelPrimary > td:nth-child(1) > nobr > span{ color: red; } \
");

//does not work
$("#T301444200 > tbody > tr.SelPrimary > td:nth-child(1) > nobr > span").css("color","blue","important");
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Ura
  • 2,173
  • 3
  • 24
  • 41
  • Possible duplicate of [Fire Greasemonkey script on AJAX request](http://stackoverflow.com/questions/8281441/fire-greasemonkey-script-on-ajax-request) – Brock Adams Feb 01 '16 at 21:39

2 Answers2

0

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.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
0

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");
});
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116