Mastering all changes to the 'src' attribute in the DOM

I am currently coding in Javascript and trying to implement a feature that monitors new 'script' elements and blocks specific sources. I have experimented with using MutationObserver and __defineSetter__, both of which can monitor changes to the 'src' attribute, but they only intercept the change after the HTTP request has already been made. This means that even if I modify the src attribute, the resource is not effectively blocked.

window.HTMLScriptElement.prototype.__defineSetter__('src', function (d) 
    {
        console.log("HTMLScriptElement: ",d);
        if (d.indexOf('localhost') != -1) {
            //BLOCK SCRIPT
        }
    });

    new MutationObserver(function (a) {
        a.forEach((e) => {
            e.addedNodes.forEach((z) => 
            {
                if (z.nodeName.toLowerCase() == "script" && z.src.indexOf('localhost') != -1) 
                {
                    //BLOCK SCRIPT
                }
            })
        })
    }).observe(window.document, {
        attributes: true,
        childList:true,
        subtree:true
    });

Answer №1

To capture network requests, consider leveraging Service workers. Here's a snippet of code that could help achieve this:

self.addEventListener('fetch', function (event) {
    const blockedUrls = [
        //...
    ];
    if (blockedUrls.some(x => event.request.url.startsWith(x))) {
        event.respondWith(new Response('blocked', { status: 401, statusText: 'Unauthorized' }));
    }
});

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

Inject a DOM event into a personalized form validator within an Angular application

I'm currently working on validating a form using the reactive approach. I've implemented a file input to allow users to upload files, with custom validation conditions in place. However, I'm encountering an issue where the validator only rec ...

Is it possible to refactor this forwardRef so that it can be easily reused in a function?

Currently, I am in the process of transitioning my application to Material UI V4 and facing challenges with moving my react router Link components into forwardRef wrapped components when setting the 'to' prop programmatically. The code below doe ...

What is the solution to fixing the JSON parsing error that says 'JSON.parse: bad control character in string literal'?

When sending data from NodeJS Backend to the client, I utilize the following code: res.end(filex.replace("<userdata>", JSON.stringify({name:user.name, uid:user._id, profile:user.profile}) )) //No errors occur here and the object is successfully stri ...

The data source is having trouble connecting to the updated JSON format due to issues with pagination

I'm utilizing pagination.js to fetch asynchronous data using the code below. $('#demo').pagination({ dataSource: 'https://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?&ap ...

What is the method to dynamically modify the value of location.href using vanilla javascript?

I have a button that looks like this: <button type="button" class="play-now-button" onclick="location.href='www.yahoo.com'">Play Now</button> However, I want to change the location.href value using vanilla JavaScript. The code below ...

The specified type '{ state: any; dispatch: React.Dispatch<{ type: string; value: any; }>; }' is not compatible with the expected type

I've been working on a UI layout that includes checkboxes on the left, a data table on the right, and a drop zone box. The aim is to keep the table data updated whenever a new file is dropped, and also filter the data based on checkbox selection. I ma ...

Are the Bootstrap columns arranged in a vertical stack instead of side by side?

I currently have two large columns that are stacked vertically on top of one another. I want them to be side by side, like | 1 | 2 |, so that the user can view both columns simultaneously. I am seeking tips or suggestions on how to resolve this issue. Whil ...

Utilizing AngularJS to implement checkbox selection within a table

I'm working on a method that will receive an Id from a table when a checkbox is checked and update the $scope.selected array in my Angular controller. If the checkbox is unchecked, it should remove the corresponding item from $scope.selected. Here&ap ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

The useContext hook was utilized in conjunction with useReducer, however, a child component is unexpectedly showing an

First and foremost, I want to express my gratitude for your unwavering support. As a newcomer to the realm of ReactJS, I am currently navigating through the development of a concept example for a product store that includes various filters in the form of ...

Dropdown in Angular JS is displaying incorrect values in the options

I am a newcomer to AngularJS and encountering an issue with populating a dropdown. Within a foreach loop of data retrieved from the server, I have created an array of user data: $scope.Users.push( { userid: ...

How can I create a custom Sweet Alert button in JavaScript that redirects to a specific webpage when clicked?

Here's what I have in my code: swal({ title: 'Successfully Registered!', text: "Would you like to proceed to the Log In page?", type: 'success', showCancelButton: true, confirmButtonColor: '#308 ...

Retrieving components from Ajax response data

While I have a good grasp of PHP, diving into AJAX and dealing with JSON is proving to be quite challenging for me. My PHP script simply delivers a straightforward JSON string like this: {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": ...

Transitioning from Global Namespace in JavaScript to TypeScript: A seamless migration journey

I currently have a collection of files like: library0.js library1.js ... libraryn.js Each file contributes to the creation of a global object known as "MY_GLOBAL" similarly to this example: library0.js // Ensure the MY_GLOBAL namespace is available if ...

Navbar collapse not functioning properly on HTML, CSS, and JavaScript

I have developed a CSS code snippet: .nav{ right: 0px; left: 0px; margin-top: 0px; margin-bottom:20px; height: 35px; text-align: center; background-color: red; z-index: 1; } .sticky { background: #000; text-align: center; ...

Access numerical values from JSON objects using JavaScript

I need assistance with implementing a JavaScript function to retrieve data from a JSON file and then display it on my webpage. The goal is to iterate through the values in a while loop and dynamically insert them into specific HTML elements. xhttp.onrea ...

What is the best way to include a variable or literal as a value in styled components?

When it comes to managing various use cases, I always rely on props. However, I am currently facing a challenge in changing the border color of a styled input during its focus state. Is there a way to utilize props for this specific scenario? Despite my f ...

What is the best way to get a string as a return value from an async function that uses the request API

I'm currently working on a project that involves printing the HTML code source as a string using the request API. I've created a function to fetch the data as a string, but when I try to print the output, it returns undefined. I'm struggling ...

Mystery Surrounding MP3 Playback in ASP.NET

Currently, I am utilizing an ASP.NET server side control to play MP3 files on my website. While I could utilize JavaScript or Flash controls for this purpose, the issue I'm facing is that I want the music to only play once (at the start of the site) a ...

jQuery Mobile is experiencing page height inaccuracies

My web application, built with jQuery Mobile 1.2.0, is encountering an issue with page height calculations on Windows Phone. While iOS and Android display correctly, there is a gap at the bottom of the page on Windows Phone. Is there a CSS-only solution t ...