What is the best way to initiate a function upon each page load?

(Apologies in advance for any English mistakes)
Hello everyone, I am currently developing a simple Chrome extension to edit certain graphics and text fields on a website (Freshdesk) that cannot be modified directly on the site due to proprietary code.
My issue lies in ensuring that the function which replaces the text is active every time the pages are displayed. Currently, I am utilizing a setInterval() with a 100 ms delay to achieve this, but it's not the most optimal solution as the function ends up running multiple times within seconds.

function main() {
  console.log('main started');

  setInterval(changeText, 100); //(Not optimized)
}

function changeText() {
  // replace 'Group' with 'Sector' in the ticket tab visual
  $('.ember-power-select-placeholder.label-field').each(function(x){
    var new_text = $(this).text().replace("Group", "Sector");
    $(this).text(new_text);
    console.log('function started');
  })
}

main();

As shown in the screenshots and code above, the task at hand is to change the text from

Group

to

Sector

Although the code does work, the issue arises when observing the console output.. (after approximately 5 seconds).

I have experimented with various methods to ensure the JavaScript runs once the page loads, but none have proven successful. Do you have any suggestions to improve this situation?

EDIT: Here is the manifest.json:

{
    "name": "DAN-Patch",
    "version": "1.0",
    "manifest_version": 2,
    "permissions": [
        "webNavigation", 
        "activeTab", 
        "background",
        "tabs"
    ],
    "content_scripts": [
        {
            "run_at": "document_idle",
            "matches": ["https://gestionaledan.freshdesk.com/*", "https://gestionaledan.freshworks.com/*"],
            "js": ["jquery-3.5.1.min.js", "content.js"],
            "css": ["stylesheet.css"]
        }
    ]
}

Answer №1

To optimize your code and streamline the process execution, consider implementing the following:

function main() {
    console.log('main started');

    let exa = setInterval(function () {
        let el = $('.ember-power-select-placeholder.label-field'),
            all = 0;

        el.each(function () {
            if ($(this).text() == "Group") {
                var new_text = $(this).text().replace("Group", "Sector");
                $(this).text(new_text);
                console.log('function started');
                all++;
            }
        });

        if (all === 0) {
            clearInterval(exa);
        }
    }, 100); //(Optimized)
}

main();

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

The download button consistently targets and downloads the initial SVG in my collection. How can I configure it to target each individual SVG for download?

I'm currently working on a QR code app using React. The goal is for users to submit a form with a value, which will then generate an SVG QR code that can be downloaded. However, I'm running into an issue where the same SVG file is being downloade ...

JavaScript function that shows the name of an individual extracted from a specific file

Hey there, currently I'm diving into a javascript tutorial and exploring ways to display a person's name along with their birthday on this historical day. <script type="text/javascript"> document.write("Today is <br/&g ...

Using relative positioning in CSS causes the div to move to a new line

Feel free to check out this demo I've created for reference: http://jsfiddle.net/jcb9xm44/ In a nutshell, the scenario involves two inline-block divs nested within a parent div: <div class="outer"> <div class="inner1"> Y & ...

Obtaining page information from a frame script in e10s-enabled Firefox: A guide

One of the challenges I'm facing is with my Firefox extension, where a function loads page information using the following code: var title = content.document.title; var url = content.document.location.href; However, with the implementation of multi- ...

The function putImageData does not have the capability to render images on the canvas

After breaking down the tileset The tiles still refuse to appear on the <canvas>, although I can see that they are stored in the tileData[] array because it outputs ImageData in the console.log(tileData[1]). $(document).ready(function () { var til ...

"Rest assured that Coldfusion 9 users may encounter a JSON parsing

I have a function that performs the following operation: <cffunction name="foo" access="remote" returnformat="JSON" > <cfreturn ["000", "001", "002"]> <cffunction> When I retrieve this array using jQuery.ajax, I noticed in Firebu ...

The JQuery duplication process did not function as anticipated

This question builds on a previous one related to jQuery cloning and incrementing IDs. The issue is that when adding new elements, the IDs are not being generated in the correct sequence. For example, if the initial ID is expy-1, clicking "add more" should ...

The marriage of Vue 2.0 and Rails 5: Shifting from Reactive to Declarative Rendering

As I make my way through the Vue guide with a Rails 5 app, I've noticed that although I am able to update my Vue js object, the DOM doesn't behave as described in the Declarative Rendering section. The data and the DOM are supposed to be linke ...

The Material UI autocomplete unexpectedly closes on click instead of displaying a popover as intended

I'm facing a challenge with adding a button to the Material UI autocomplete using the renderOption prop. I added a button to each row that was intended to display a PopOver component, but when clicking on the button, it automatically closes the autoco ...

Issue with Node REST API: PUT request is failing to update data in the request

Encountering issues while attempting to update data through a PUT request. Despite making the request, the data remains unchanged and continues to display the previous information in Postman. Details of the PUT request sent via Postman: http://localhost: ...

How can we develop an AJAX chat with enhanced scrolling capabilities?

Could someone provide me with some examples on how to achieve this task? I already have some HTML code: <div id="chatDisplay"> </div> <input type="text" id="message" /><input type="button" id="send" value="Send" /> Next, I have so ...

Enhancing the appearance within an HTML input element

Let's consider a scenario where we have an input element with the following text: <input type="text" value="Lucas"> Is there a way to emphasize the "L" in the value as Bold, similar to Lucas? We are familiar with how this can be achieved usin ...

Modify opacity of displayed items in image list with ng-repeat

My application showcases a list of images using ng-repeat. +---------------------------------------------+ | | Previous Image 0 | | | +------------------------------------+ | | +------------------------------------+ | | ...

Disabling a button after clicking using jQuery

There are occasions when I can inadvertently trigger the submit button twice, resulting in the ajax being triggered twice as well. Below is my HTML code: <div class="buttons-area"> <input id="step-two" class="btn btn-primary" type="submit" v ...

Tips for accurately dissecting a PDF document to determine the status of checkboxes

Looking for a solution to parse PDF forms on the server side, I have experimented with various node.js modules including pdf2json, hummus, and node-pdftk. While I have successfully retrieved all text fields, I am facing issues when it comes to extracting c ...

Order the rows being inserted into a table by iterating through them using a foreach loop directly from the

I am currently working on a table that receives its data from a database. The table structure includes the typical header row, and then I use a foreach() loop to fetch information from an included file and display it in the table body (with a new row for e ...

Can you explain the purpose of the URL function in the context of url("#foobar"

Currently, I am developing a CSS concatenator and one of the tasks involved is URL to absolute URL rewriting. For this process, I exclude any absolute URLs that start with http, https, etc. In the case of Django projects, they designate the following URL ...

What is the reason behind the body element's background styling impacting the entire screen?

Why does styling the background of the body element affect the entire screen instead of just the body itself? For example, consider this CSS rule: body { width: 700px; height:200px; border: 5px dotted red; background-color: blue; } While the ...

Creating an email body using css and html from a file on Android - how can it be done?

After searching extensively, I have come across a plethora of solutions on how to load HTML into the body of an email intent. However, I am struggling to find a way to load a file that contains CSS and HTML content. I have a specific program in which I dis ...

Updating the @mui/x-data-grid table dynamically upon fetching new data

Seeking assistance regarding updating data in the DataGrid component from the @mui/x-data-grid module within a React application. Specifically, I am facing challenges in refreshing the table after retrieving data from an API using react-query. Despite succ ...