Exploring the world of DOM manipulation in AJAX websites?

Hello everyone, I am fairly new to developing extensions but I am eager to learn. I am currently working on creating an extension that specifically blocks certain Twitter icons. Through a helpful tutorial, I have been able to gather a lot of information. I have successfully extracted tweets from the DOM, checked for usernames, and disabled the display of specific images using JavaScript.

I have made progress by setting up a mock page, which I have named twitter.html, designed like this:

<html>
    <div class="stream-item" data-item-type="tweet">
        <div class="tweet-image">
            <img src="abc.jpg" data-user-id="1234">
        </div>
    </div>

.....

<script src="utility.js"></script>
<script type="text/javascript">
var tweets = getElementsByClass("tweet");
for (var i =  0; i < tweets.length; i++) {
    var tweet = tweets[i];
    var name = tweet.getAttribute("data-screen-name");
    if (name.toLowerCase() == 'some-username'.toLowerCase()) {
        var icon = tweet.getElementsByTagName("img")[0];
        icon.style.display='none';
    }
}

</script>

</html>

While I have successfully hidden the images, I am struggling with getting the code to run at the right time. I am using the Safari extension builder which allows me to provide a main page, as well as before-load and after-load JS files. However, the page load completes before any tweets are loaded due to the AJAX operations used by the actual twitter.com website.

How can I ensure that my JS code runs after the tweets have been loaded?

Answer №1

For effective monitoring of DOM changes, it is recommended to utilize the DOMNodeInserted event, triggered every time a new DOM Node is inserted. Upon receiving this event, it is important to verify if the inserted node is relevant to your requirements before taking any further actions.

I have taken the initiative to adjust your code to incorporate these insights. The revised code has been successfully tested in the Chrome browser.

window.addEventListener("DOMNodeInserted",
    function(event){ 
        var streamItem = event.target;
        if (streamItem == null)
            return;

        if (streamItem.getAttribute('class') != 'stream-item')
            return;

        var tweet = streamItem.getElementsByClassName("tweet",streamItem)[0];
        var name = tweet.getAttribute("data-screen-name");
        if (name.toLowerCase() == 'some-username'.toLowerCase()) 
        {
            var icon = tweet.getElementsByTagName("img")[0];
            icon.style.display='none';
        }
    }, 
    false);

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

Exploring the methods to access GuildMember roles along with their respective details

const Discord = require('discord.js'); const bot3 = new Discord.Client(); const token3 = 'I am not disclosing my bot's token'; const mark2 = '*info personal' bot3.on('message', msg =>{ let args2 = msg.co ...

Encountering an issue during the installation of the live-server package through npm. Despite running `npm audit`, the error still persists and remains

I'm a beginner in the world of JavaScript and I've been following a tutorial here to learn more. I'm currently trying to install the live-server package using npm, but I keep encountering the following error message. $ npm install -g live-se ...

Require a v-alert notification to appear on every page, ensuring visibility across the site

Imagine a scenario where there is a right drawer that displays a grade dropdown with options like grade1, grade2, and grade3. On all pages, I need a v-alert notification strip to show the total count of students. For example, if I select grade3 from the ri ...

Guide on establishing a connection with a TCP server and sending a JavaScript script to it

I am completely new to JS and node. I am using SkyX Pro, a telescope management software that has the capability to run a TCP Server on port 3040. By connecting with Netcat and providing it with Javascript starting with //* Javascript *//, I can control ca ...

Ways to resolve the error "Uncaught TypeError: data.map is not a function"

Currently developing an app using reactJS and encountering the following error in the console when using the map function: TypeError: data.map is not a function. Despite successful API data calling as confirmed by console.log, the error persists when tryin ...

Exploring the assortment of reactions post-awaitReaction in node.js

The current code runs smoothly, but I encounter an issue when attempting to send messages after selecting either the X or check option. Instead of the expected outcome, I receive Despite my understanding that this collection is a map, all attempts to acce ...

JavaScript tri-state toggling

After devising 2 buttons, each intended to toggle a heading or paragraph, I encountered a slight issue. When using the 'Toggle Para' button, the switch occurs between 2 paragraphs upon 2 clicks. However, on the third click, I desire for both para ...

Is there a way to retrieve two separate route details using jQuery simultaneously?

Clicking the checkbox should display the Full Name: input type="text" id="demonum" size="05"> <button type="button" onclick="load_doc()">click</button><br><br> <input type="checkbox" id ="check" > The r ...

Querying MongoDB using JavaScript function

Currently, I am utilizing a MongoDB query within a JavaScript function. The script is structured as follows: var continous = ['b', 'e', 'LBE']; continous.forEach(e => izracun(e)); function izracun(atr) { var query1 = ...

Revitalize PHP through jQuery and refresh the image with a reload

I am currently working on a PHP page located at /var/www/oggi1ora.php. My goal is to run the page /usr/local/bin/oggi1ora.php every 5 seconds to generate a chart. Although the PHP script is executing correctly every 5 seconds, the image on the page is no ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

Adjust the Bootstrap date-time-picker to accommodate various languages, while ensuring that the selected date and time are displayed in English

As I work on my app, I've implemented localization support for multiple languages. When initializing the datetimepicker in the app, I provide the current language like this: datetimepicker({ locale: languageObj.language, format: 'DD MMM ...

Leveraging the power of express, employing the await keyword, utilizing catch blocks, and utilizing the next

I am currently developing an express JS application that follows this routing style: router.post('/account/create', async function(req, res, next) { var account = await db.query(`query to check if account exists`).catch(next); if (accoun ...

How to Trigger a Function in Backbone.js Upon Page Load

My function uses the simple selector $(.some-class) instead of this.$(.some-class). When I call this function in the render, it does not find the .some-class. It seems like the function needs to be called when the DOM is fully loaded. How can I achieve tha ...

Animating jQuery Counter with Changing Background Color

I've implemented a Counter that counts from 0 to a specified number, and it seems to be working perfectly. However, I want to add an animation where the background color of a div height animates upwards corresponding to the percentage of the counter. ...

Unable to locate FFmpeg on the root server for Discord JS v13

After setting up my DiscordJS Bot on a new rootserver, I transferred all the files and launched the bot. Everything seemed to be working fine until I tried to run a command that involved the bot joining a voice channel and playing audio. At this point, an ...

What is the process for changing to a different page in NativeScript?

Having trouble creating a simple button in NativeScript labeled 'login'? I've created a login component, but when testing the code, it shows an error stating "no known component for element Login." <template> <Page> <TabV ...

What is the best way to send a file object to a user for download?

When working within a route: app.get('some-route', async (req, res) => { // ... } I am dealing with a file object called file, which has the following structure: https://i.stack.imgur.com/ByPYR.png My goal is to download this file. Cur ...

Struggling with incorporating a print preview feature using JavaScript?

I am currently working on adding a print preview feature to a page that opens in PDF format. Unfortunately, I am facing an issue where the print function does not execute and nothing happens when the page is opened. I am using Python in conjunction with ...

Ways to showcase INPUT TYPE when making a Selection?

I've been struggling with a simple issue and despite trying multiple solutions, I can't seem to get it right. I have a form where I'm using the <select> tag with two options: coo and uh. What I want is for an additional input type fiel ...