Chrome Extension Tip: Reloading or re-executing a content script when an Ajax request is made

My goal is to run a content script on a specific website (like injecting a button or changing a link), but I want this to happen while the user is browsing the site.

The issue is that the webpage is dynamically constructed with ajax requests as the user navigates through it.

In a previous extension I developed, I addressed this by directly injecting my JavaScript code into the webpage itself.

I'm now exploring if there's a more efficient method, like being able to listen for an ajaxComplete event in my content script and then re-executing it when needed.

I've tried using the following approach:

function listener()
{
    console.debug("listener fired.");
}
document.addEventListener("DOMSubtreeModified", listener, false);

Unfortunately, this method triggers too frequently during a single page load.

Answer №1

Currently, there is not an ajax listener that I am familiar with. However, even if there was one, it may not be very helpful as the key is to detect when a page is modified rather than just monitoring ajax requests being sent or received (page modifications often occur later and may not be directly related to ajax requests).

DOMSubtreeModified is the recommended approach, but it is important to implement some safeguards against excessively frequent calls:

function listener()
{
    console.debug("listener fired.");
}

var timeout = null;
document.addEventListener("DOMSubtreeModified", function() {
    if(timeout) {
        clearTimeout(timeout);
    }
    timeout = setTimeout(listener, 500);
}, false);

With this method, the listener will only trigger if no other events occur within a 500ms timeframe.

Answer №2

I came across a fascinating solution that involved utilizing message passing between content scripts and the background.html file.

Below is the code along with an explanation:

Background.html

  function updatePageAction(tabId)
  {
    chrome.tabs.sendRequest(tabId, {is_content_script: true}, function(response) {
      if (response.is_content_script)
        chrome.pageAction.show(tabId);
    });
  };

  chrome.tabs.onUpdated.addListener(function(tabId, change, tab) {
    if (change.status == "complete") {
      updatePageAction(tabId);
    }
  });

content_script.js

// The background page is asking us to find an address on the page.
if (window == top) {
  chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
        if (req.is_content_script)
            start_content_script();
            sendResponse({is_content_script: true});
  });
};

The challenge was updating or re-executing the script on DOM changes where a URL change occurred. Fortunately, the URL change triggered an onUpdated event. To ensure we only focus on the relevant tab with our content scripts matched, we can specify a match in the manifest.

By sending a message to the current tab's executed content_script, we ask "Are you my content script? If so, please restart."

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 dynamic import() syntax is not compatible with the target environment, preventing the use of external type 'module' in a script

I am currently facing an issue with my React app. The command npm start is working as expected, but when I try to run npm run build, it keeps failing. It's crucial for me to run npm run build in order to deploy the app on a website. I have already sp ...

Tips for remaining on the current page after sending a post request using Express

I have a simple question that I haven't been able to find a satisfactory solution for. I've created a post route using express, like this: app.post('/search', function(req, res){ // Code to extract data from req and save it to the d ...

Creating dynamic qtip2 tooltips is an effective way to enhance user interaction on

I am facing an issue where all tooltips work perfectly fine when the page loads, but stop working after data refreshes through ajax. How can I resolve this problem? $(document).ready(function() { // MAKE SURE YOUR SELECTOR MATCHES SOMETHING IN YOUR HT ...

Handling a 404 error for a particular URL within nginx

location ~* ajax.php { if ($args ~ "action=query_new") { return 404; } } In the test directory of example.com site, there is an ajax.php file. The intention is to issue a 404 error for any requests made to ajax.php that include the query s ...

Implementing Yii pagination with asynchronous loading

Can anyone help me enable pagination using Ajax in my code? I have a Controller that updates content via Ajax. function actionIndex(){ $dataProvider=new CActiveDataProvider('News', array( 'pagination'=>array( ...

The HtmlUnit Ajax call in Java does not appear to render properly on the HtmlPage

My goal is to scan a webpage using HtmlUnit 2.31 by simply obtaining an HtmlPage via URL. The issue arises when the page triggers AJAX calls (without user interaction). I need to wait for these calls to complete and see the resulting values. Below is my co ...

What would be more efficient for designing a webpage - static HTML or static DOM Javascript?

My burning question of the day is: which loads faster, a web page designed from static html like this: <html> <head> <title>Web page</title> </head> <body> <p>Hi community</p> </bo ...

JavaScript: Efficiently Sorting a Multidimensional Array

Here is the array that needs to be sorted based on the third item: const array = [ [1, "Convention Hall", "Mumbai", 10, "XYZ Company"], [2, "Auditorium", "Delhi", 10, "ABC Company"], [3, "CenterHall", "Bangalore", 10, "ZZZ Company"], ... ...

How can I incorporate percentage values into input text in Angular?

How can I include a percent sign in an input field using Angular, without relying on jQuery? I am looking for a solution that is identical to what I would achieve with jQuery. Here is the current status of my project: ...

Unique markers for Google Maps

I have been working on creating custom Google maps with the concept of incorporating 3 distinct markers such as forests, rivers, and lakes. While I have successfully added these custom markers using a helpful tutorial, I am now facing a challenge with sor ...

Adjusting color schemes for Twitter Bootstrap Tooltips according to their placement

I have been attempting to customize the colors of tooltips (specifically from Twitter Bootstrap), but I am encountering some difficulties. While changing the default color was straightforward, altering the colors for .tooltip and its related definitions ha ...

Difficulty surfaced in the React project following relocation to a different device

I'm new to using React and webpack with babel loader in my app. My project was running smoothly until I changed machines. I copied all the files except for node_modules (which I installed with npm install). Now, when I try to run or build the projec ...

Please ensure all three of the last checkboxes are ticked before finalizing submission

Here is the list of checkboxes for my PHP form. I am trying to figure out how to write a script that will only allow the form to be submitted if the last three checkboxes are checked. I have tried looking at similar questions but haven't found the sol ...

Passing the Authorization Header for DataSource in GrapeCity's ActiveReportsJSLearn how to pass the

Our UI developer is working with VueJS, and we specifically need guidance on integrating JWT authentication within the ActiveReportsJS report viewer or designer. This is crucial as it's all based on JavaScript. We are currently utilizing JWT's w ...

Guide to accessing child prop reference in Vue 3 using Element Plus UI library

I am encountering an issue with a dropdown component labeled 'dropdown' When selecting an item, I need to retrieve the selected label (not just the value) Currently, when using dropdown.value, I receive an object containing a key and its corres ...

An issue occurred during compilation with 1 error: The required dependency could not be located

Encountering an issue in a Vue component while attempting to import another JavaScript file located in the services/AuthenticationService directory. Error message: Module not found: Error: Can't resolve '@/services/AuthenticationService'. ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

"Seamless responsiveness in design with jQuery, but encountering compatibility issues

My usage of jQuery is quite basic to ensure that elements are properly positioned when they are moved: function ipad() { var width = jQuery(window).width(); if (width < 1200 && width >= 768){ //if tablet jQuery('.mobbut').css(&apo ...

I am facing a situation where I need to apply identical ngStyle to two different elements. How can I avoid repetition and maintain code efficiency?

I am looking to customize the ngstyle <p class="is-discount" [ngStyle]="{ 'background-color': bicycle.discount > 70 ? 'red' : bic ...

JavaScript code that involves manipulating dates within a nested loop

I'm currently developing a booking system where the pricing varies based on seasons that recur annually. The overall functionality is working smoothly, however, I am encountering difficulties with handling the recurring seasons. I have implemented mom ...