Userscript to append() on freshly-loaded Facebook timeline elements

91 views Asked by At

I'm coding a userscript to help Facebook groups' admins perform several actions directly on the post. It's aim is to add buttons to ban users, delete posts etc. near the post author's name (when browsing group posts). I've already coded the addition of the buttons near the user's name using jQuery's append() function and it's working - it adds the buttons to first 14 persons, but when scrolling down, Facebook loads the rest of the posts and there are no buttons.

My code:

// ==UserScript==
// @name              admin addon
// @namespace         http://facebook.com/
// @version           1.0
// @description       an addon that makes you perform admin actions with an ease
// @author            mhwq
// @match             https://www.facebook.com/groups/1734441496799901/*
// @require           http://code.jquery.com/jquery-latest.js
// @require           http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js
// @grant             GM_addStyle
// @grant             GM_getResourceText
// ==/UserScript==

$(document).ready(function() {
    $( ".fwb.fcg" ).append(' here go the buttons!');
});

What now?

Is there any way to make the buttons appear on every group post, even on these ones, that were loaded in result of scrolling down?

1

There are 1 answers

0
Brock Adams On BEST ANSWER

Those posts are loaded by AJAX, so you need to use AJAX-aware techniques, like MutationObserver or waitForKeyElements().

Using waitForKeyElements, your script becomes:

// ==UserScript==
// @name            Facebook admin addon
// @description     an addon that makes you perform admin actions with an ease
// @author          mhwq
// @match           https://www.facebook.com/groups/1734441496799901/*
// @require         http://code.jquery.com/jquery-latest.js
// @require         http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js
// @require         https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant           GM_addStyle
// @grant           GM_getResourceText
// ==/UserScript==

waitForKeyElements (".fwb.fcg", appendButtons);

function appendButtons (jNode) {
    jNode.append ('Here are the buttons!');
}