Userscript works only on pages served from backend, but not on frontend in a SPA way

Viewed 1230

I have the following userscript I run on Greasemonkey/Tampermonkey.

I run it on facebook.com which serves some of the webpages from backend, in bootstrapping, and some others on the fly, in front-end, via HRO, just as a Single Page Application (SPA) would.

// ==UserScript==
// @name        facebook
// @namespace   nms
// @include     http://*.facebook.com/*
// @include     https://*.facebook.com/*
// @version     1
// @grant       none
// ==/UserScript==

setTimeout( () => {
    // generalStuff:
        document.querySelectorAll(' #left_nav_section_nodes, .fbChatSidebar ').forEach( (e)=> {
            e.style.visibility = "hidden";
        });

}, 1000);

If I run this script on console, even in HRO based webpages, it runs fine, but when runned from Greasemoneky/Tampermonkey it won't run in these particular webpages.

How could I make the script to work without problem on SPA-like webpages as well?

2 Answers

For a similar use case, I used MutationObserver and checked node.baseURI of each node in each mutation.addedNodes.

(async function() {
    'use strict';
    const selector = '.quiz--answered';
    const observer = new MutationObserver(mutations => {
        if (!mutations.some(mutation => Array.from(mutation.addedNodes).some(node => node.baseURI.includes('/quiz/')))) {
            return;
        }
        const elm = document.querySelector(selector);
        if (elm) {
            // work with elm
        }
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
})();
Related