The userscript is designed to function exclusively on pages originating from the backend, rather than on the frontend in a single-page application

I have a userscript that I use with Greasemonkey/Tampermonkey.

It's set to run on facebook.com, where some pages are served from the backend during bootstrapping and others are loaded on the fly in the front-end using HRO, similar to how a Single Page Application (SPA) functions.

// ==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);

When I manually run this script in the console on SPA-like webpages, it works without any issues. However, when I try to execute it through Greasemonkey or Tampermonkey, it doesn't work on these specific types of webpages.

Is there a way to modify the script so that it functions correctly on SPA-style webpages as well?

Answer №1

When traditional methods like setTimeout, setInterval, and event delegation fail to work on their own, there is a workaround available. By pushing a state that includes these methods into memory, we can then replace the current state with it, effectively causing a change in the webpage's DOM content.

Here is a piece of code used to swap data loaded via AJAX instead of directly from PHP:

let utilityFunc = ()=> {
    var run = (url)=> {
       // insert your code here
    };

    var pS = window.history.pushState;
    var rS = window.history.replaceState;

    window.history.pushState = function(a, b, url) {
        run(url);
        pS.apply(this, arguments);
    };

    window.history.replaceState = function(a, b, url) {
        run(url);
        rS.apply(this, arguments);
    };

utilityFunc();

This information was gathered while reading here.

Answer №2

Another scenario where I had to tackle a similar issue involved utilizing the MutationObserver and inspecting the node.baseURI of each node within the mutation.addedNodes.

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

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

Answer №3

Encountering this issue multiple times led me to create a custom solution. I developed a simple library that enables me to execute scripts on URL changes, specify URLs using wildcards, and wait for specific elements if needed. This library is known as spa-runner.

import { run } from "@banjoanton/spa-runner";


const handler = () => {
    console.log("hello world!");
}

const config = {
    urls: ["http://*.facebook.com/*"],
    runAtStart: true,
};

const unsubscribe = run(handler, config);

Answer №4

After going through this specific documentation, it is clear that this code is designed to function effectively for single page applications when changing the location:

// ==UserScript==
...
// @match        https://subdomain.domain.tld/*
// @match        http://subdomain.domain.tld/*
// @grant        window.onurlchange
// ==/UserScript==

(function() {
    'use strict';
    if (window.onurlchange === null) {
        window.addEventListener('urlchange', (info) => {
            if (Object.values(info)[0].includes("/path/to/certainlocation")) {
                // your code here
            }

        });
    }
})();

It's important to note that this may not be effective if you directly visit the certain location, but adjustments can be made to address that issue. Alternatively, a separate userscript could be created that specifically targets that particular location, like so:

// @match       https://subdomain.domain.tld/path/to/certainlocation
// @match       http://subdomain.domain.tld/path/to/certainlocation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a Material UI Tooltip to the header name of a Material UI Datagrid - a step-by-step guide!

I've nearly completed my initial project, but the client is requesting that I include labels that appear when hovering over specific datagrid cells. Unfortunately, I haven't been able to find any solutions on Google for adding a Material UI Tool ...

How can we add up the sum with just one click and then display the

Is there a way to calculate numbers within specific DIV boxes and display the total in a separate DIV when a box is clicked? I've attempted different methods, including enclosing the code within the window.onclick function. Check out my code on this J ...

Tips for transferring data from a service to a method within a component

I have a service that successfully shares data between 2 components. However, I now need to trigger a method in component A when an event occurs on the service (and pass a value to that component). Can someone guide me on how to achieve this? I have seen ...

Struggling to create a BMI Calculator using JS, the result is consistently displaying as 'NaN'

Having trouble creating a BMI Calculator using JavaScript. The issue I'm facing is that the calculation always returns 'NaN'. I've tried using parseInt(), parseFloat(), and Number() but couldn't solve the problem. It seems that the ...

Integration of Angular.js functionalities within a Node.js application

After working on my node.js app for a few weeks, I decided to add some additional features like infinite-scroll. To implement this, I needed to use packages in node.js along with angular.js. So, I decided to introduce angular.js support to the app, specifi ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

What is the best way to select a specific button to handle the onSubmit event in a React form with multiple buttons

Imagine having the following HTML structure: <div id="container"></div> <p>Output: <span id="output"></span></p> accompanied by this block of JS code: function otherAction(e) { document.getElementById('output& ...

How can you prevent JQuery AJAX from automatically redirecting after a successful form submission?

Encountered an issue with loading http://example.com/signup.ashx: The redirect from 'http://example.com/signup.ashx' to '' was blocked by the CORS policy. This is due to the absence of 'Access-Control-Allow-Origin' header on t ...

Utilize the onClick event to access a method from a parent component in React

Looking for guidance on accessing a parent component's method in React using a child component? While props can achieve this, I'm exploring the option of triggering it with an onClick event, which seems to be causing issues. Here's a simple ...

Connect a nearby dependency to your project if it has the same name as an npm repository

What is the best way to npm link a local dependency that has the same name as a project in the npm registry, like https://registry.npmjs.org/react-financial-charts? Here is an example: cd ~/projects/react-financial-charts // Step 1: Navigate to the packa ...

Steps to implement jQuery after executing the command "npm install jquery"

Greetings! I recently utilized npm install jquery to add jQuery to my project. However, I noticed that it was downloaded into node_modules\jquery along with some unnecessary files. My goal is to only move node_modules\jquery\dist\jquer ...

Create a dynamic editing experience using PHP and AJAX, allowing users to make

Is there a way to update my database table without having to refresh the page? I seem to be encountering issues with my script, as the popup and database selection work fine, but nothing happens when I hit submit. It doesn't redirect me to the edit.ph ...

How can I extract data from [Object object] in Node.js?

Can someone help me figure out how to extract data from [Object object]? Let's consider the following scenario for clarity. // Fetching data using dirty method var info = database.get('/htmltest') // Contents of test.db file {"key":"foo", ...

Adjust the content of an iframe based on the size of the screen

Hi there, I'm currently facing an issue with an ad that can't be resized. The support team suggested using two different ads - one for mobile and one for desktop. The dimensions of the ads are 720 x 90 and 300 x 100. I would like the ad to automa ...

React SlideMenu will not close when a link is clicked

I am facing an issue with my off-canvas menu, which slides in when the variable isOpen is set to true. However, the problem arises when trying to slide it back out upon clicking a Link to navigate to another page. Instead of sliding out, the mobile menu oc ...

I need help figuring out how to mention an id using a concatenated variable in the jquery appendTo() method

Using jQuery, I am adding HTML code to a div. One part of this code involves referencing a div's ID by concatenating a variable from a loop. $(... + '<div class="recommendations filter" id="recCards-'+ i +'">' + &apo ...

Guide: Implementing Paginated Search with Azure Search in PHP

I'm presenting a snippet of PHP code for reference: public function getListFromAzure($searchParameter, $categoryList, $request){ $jobListingManager = $this->get('recruitday.model_manager.job_listing'); $url = $jobListingManager- ...

Creating a nested function and utilizing the return statement in JavaScript

I am facing an issue with my custom function that contains an ajax call. I need to retrieve a variable from the ajax function within my custom function, but I'm unable to do so. Why is this happening? Possible solution 1: <script> function ...

Transmit information from the frontend to the backend using JavaScript and the Express framework

After creating a custom variable in my frontend to store data, I needed to access the same data in my Express backend. The JavaScript variable and the POST request code snippet are as follows: const dataPush = { urlSave: urlSave, ...

Error with JSON parsing in JavaScript when processing large numbers

After requesting a list of approved tweets from a webserver in JSON format, I visited the URL: http://localhost:8000/showtweets/?after_id=354210796420608003 and received the following JSON response: [{ "date": "2013-07-08T12:10:09", "text": "#R ...