Click A Button On Dynamically Changed Element

When you link to some site on the Facebook chat, I always click the small x so the preview disappears. I hate doing this, as I send probably hundreds of links every day, and the previews are just rubbish 9/10 times.

I am creating an userscript to fix this, but since it's loading dynamically, I cannot simply click the button when it appears. This is what it looks like when I want to click the button:


Basically it finds the class fbNubFlyoutAttachments and then finds the button containing "Remove". Then it clicks the element and the preview disappears. Pretty easy.

However, when I get to the point of checking when a link has been posted.. we're getting into some tricky stuff here. This is what I have tried so far:

$(document).bind("DOMSubtreeModified ", ".fbNubFlyoutAttachments", function(){

However. $(document).bind("DOMSubtreeModified" triggers a lot, since the DOM changes a lot, which causes the stack to be filled pretty much instantly, and then the page freezes up. It would be nice to just do $(".fbNubFlyoutAttachments").bind("DOMSubtreeModified" but that is not possible (to my knowledge).

This is what I currently do, which works, but could take up to a second to trigger and it's using computing resources without the need for it:

setInterval(function() {
}, 1000);

How can I do this in a good way through my userscript? Any help is appreciated! Thanks.



Instead of use DomSubtreeModified event which is deprecated you can use MutationObserver.

DOM mutation events has a problems with performance and stability so this is probably the reason why all freezes when you bind DomSubtreeModified event to document, more info here.

So you can try to use MutationObserver in tampermonkey as follows:

// ==UserScript==
// @name         New Userscript
// @namespace
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match*
// @grant        none
// @require

// ==/UserScript==
/* jshint -W097 */
'use strict';

$(function() {
    // element to observer
    var body = document.querySelector('body');

    // create the trigger function
    var observer = new MutationObserver(function(mutations, observer) {

    // configure the element to observe and the changes you want to check
    observer.observe(body, { subtree: true, childList : true, characterData : true});


Check also the attributes of the observer method.

Additionally you can filter the actions depending on the mutations array of object received in MutationObserver callback.

Hope it helps,