In a userscript, I do lots of detection of element changes using waitForKeyElements().
However, I’ve run into a specific example where waitForKeyElements doesn’t reliably fire on change.
My userscript adjusts theirID to insert the internal span, such as you see here:
<span id='theirID' class='myclass'>
<span class='myclass2'>text</span> more text
</span>
The site then changes this code to erase my internal span, so that it then looks like:
<span id='theirID' class='myclass'>
some text
</span>
For some reason, on some cases, waitForKeyElements just doesn’t get triggered on that change. I’ve tried to detect changes on the outer span, the inner span, the outer span’s parent, its parent, etc.
So I’m now wondering if there’s some other way to detect, for example, whether the element w/ myclass2 (the inner span) has vanished? I could poll $('.myclass2').length I suppose, but I wouldn’t know where in the document it vanished from. I’d ideally know the specific parent that held the now-missing item.
Any ideas?
Here are two answers, one for this specific case (you’re using
waitForKeyElements, and another for the general case.For this specific case:
Since you are using
waitForKeyElements()already, you can take advantage of the return value in the node handler.Suppose the target page originally had HTML like this:
And your script used
waitForKeyElements()like this:Yielding:
Then, you could:
wrapImportantWordsreturntrue— which tellswaitForKeyElementsthat the node was not found after all, so it keeps checking.span.myclass2is (still) present.Like so:
Detecting vanished elements in general using the new MutationObserver:
In your specific case, this seems to be overkill. But, here’s a method for general reference.
Notes:
In this case, we want to know when
span.myclass2s are deleted so we observe their parents (span.myclass).Here is a complete Firefox Greasemonkey script. You can test it against this page. (Note that the Chrome code is the same except for the usual changes due to the lack of
@require.)