blues
blues

Reputation: 5185

Make Greasemonkey react to ajax change of an element

There is a page that loads with an empty span like this: <span id="bla"></span> and later fills that span with some text.

I need my script to get that text but Greasemonkey runs before it is filled with the text and even the waitForKeyElements function, that I tried to use, is not helping because the element is already there when the page loads.

Maybe I need in another way? Currently I am doing:

waitForKeyElements ("#bla", get_span_content)

Upvotes: 2

Views: 1734

Answers (1)

Brock Adams
Brock Adams

Reputation: 93443

Since you are already using waitForKeyElements, use the action-function's return value to fine tune the results. If the span is only filled/changed once, the code would look like this:

 waitForKeyElements ("#bla", get_span_content);

 function get_span_content (jNode) {
     var spanText   = $.trim (jNode.text () );

     if (spanText == "") {
        //-- Still blank; tell waitForKeyElements to keep looking.
        return true;
     }
     else {
        //  DO WHATEVER WITH spanText HERE.
     }
}



If the same span is changed multiple times, the code would look like this:

 waitForKeyElements ("#bla", get_span_content);

 function get_span_content (jNode) {
     var spanText   = $.trim (jNode.text () );
     var lastText   = jNode.data ("lastText")  ||  "";

     if (spanText != lastText) {
         //  DO WHATEVER WITH spanText HERE.

         jNode.data ("lastText", spanText);
     }

     return true;
}

Upvotes: 2

Related Questions