Changing XMLHttpRequest Prototype in Chrome Extension for Enhanced Functionality

As I strive to intercept all XMLHttpRequests using my extension, I have managed to achieve partial success with my current implementation. However, it is not working as intended. While I am aware of webRequests, they do not allow me to modify the post/get data like in the code snippet below. The following code can be executed:

Inject.js

(function(){
    console.log("Injected Send")
    var proxiedSend = window.XMLHttpRequest.prototype.send;
    window.XMLHttpRequest.prototype.send = function() {
        console.log(this, arguments );
        return proxiedSend.apply(this, [].slice.call(arguments));
    }
})();
(function(){
    console.log("Injected Open")
    var proxiedOpen = window.XMLHttpRequest.prototype.open;
    window.XMLHttpRequest.prototype.open = function() {
        console.log(this, arguments );
        return proxiedOpen.apply(this, [].slice.call(arguments));
    };
})();

When this piece of code is included in my content script, it will display "Injected Send" and "Injected Open". However, upon testing, it exhibits erratic behavior.

If you were to run the code snippet below in the console, you would observe that it successfully intercepts requests made but fails to work on XMLHttpRequests initiated on the page (both new and old objects). It only intercepts XMLHttpReuests initiated through the console. An example of this is provided here: https://www.w3schools.com/code/tryit.asp?filename=GBUKE1JS7IFL. Although it works within the webpage, replicating the same behavior by injecting it via an extension seems challenging.

(function(){
    console.log("Injected Send")
    var proxiedSend = window.XMLHttpRequest.prototype.send;
    window.XMLHttpRequest.prototype.send = function() {
        console.log(this, arguments );
        return proxiedSend.apply(this, [].slice.call(arguments));
    }
})();
(function(){
    console.log("Injected Open")
    var proxiedOpen = window.XMLHttpRequest.prototype.open;
    window.XMLHttpRequest.prototype.open = function() {
        console.log(this, arguments );
        return proxiedOpen.apply(this, [].slice.call(arguments));
    };
})();

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log("success")
    }
};
xhttp.open("GET", "/", true);
xhttp.send();

This perplexing issue is hindering the functionality of my Inject.js.

manifest.json

{
  "name": "test",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "testing xmlhttprequests",
  "homepage_url": "http://example.com",
  "icons": {
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  },
  "default_locale": "en",
  "background": {
    "scripts": [
      "src/bg/background.js"
    ],
    "persistent": true  
  },
  "page_action": {
    "default_icon": "icons/icon19.png",
    "default_title": "page action demo",
    "default_popup": "src/page_action/page_action.html"
  },
  "permissions": [
    "tabs",
    "*://*.google.com/"
  ],
  "content_scripts": [
    {
      "matches": [
        "https://*/*",
        "http://*/*"
      ],
      "run_at": "document_start",
      "js": [
        "src/inject/inject.js"
      ]
    }
  ]
}

Answer №1

To successfully execute it, run the code within a DOM script as outlined in this helpful resource: Insert code into the page context using a content script.

-wOxxOm

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

Updating charts in React using Chart.js with the click of a button

I am currently learning React and Chart JS, but I have encountered an issue. I am unable to change the data by clicking on a button. Initially, the graph displays: var Datas = [65, 59, 80, 81, 56, 55, 69]; However, I want to update this graph by simply p ...

Angular ERROR: Trying to access rating property of an undefined value

I'm encountering an issue on a website where users can vote for their favorite animal. Whenever I try to select an animal to vote for, I receive an unclear error message that has been difficult to resolve even after searching online for a solution. A ...

Vue - Enhanced Image Cropper (Error: Unable to retrieve image result from this.$refs.cropper)

I have a crop function for Vue Advanced Cropper similar to the one below: crop() { const { canvas } = this.$refs.cropper.getResult(); if (canvas) { const form = new FormData(); canvas.toBl ...

Text transitions in a gentle fade effect, appearing and disappearing with each change

I want to create a smooth fade in and out effect for the text within a div when it changes or hides. After researching on Google and Stack Overflow, I found that most solutions involve adding a 'hide' CSS class and toggling it with a custom func ...

Showing information individually for each record using jQuery or JavaScript

Hello everyone, I am looking for a solution on how to display the data only once instead of multiple times like in the screenshot attached. Currently, I am displaying the data by hovering over the corresponding markers on the map. Hey there! I have made s ...

Notes on using touch devices with Angular

My goal is to make my Angular application capable of displaying a footnote on mobile devices when text injected with nativeElement.innerHTML is clicked. I attempted to explain this before but feel that I didn't do it justice, so here's another sh ...

Utilizing jQuery's map function to extract data attributes from lists and store them in an array

View the working example Check out the failed example I'm currently utilizing a pie chart plugin available on GitHub. My objective is to generate an array resembling the structure below: [["Male",12,"some text","#222"], ["Fe ...

The Axios.delete encountered a problem while attempting to delete data from the database, showing the error message "Error:

My current tech stack includes Vue 2.3, MongoDB, Node.js, Express, and Handlebars. Initially, I was using handlebars but now I want to switch to Vue. <form class="center" action="/audioannotations/delete/{{_id}}?_method= ...

Conceal player controls for HTML videos on iOS devices

How can I hide the video player controls in Windows and Android, they are hidden but still visible on iOS. I have tried different methods but can't seem to hide them. Here is what it looks like on iOS: https://i.sstatic.net/Uwrg3.png Here is my code ...

Node.js "unexpected symbol error" (seeking assistance)

While working on my Discord bot, I encountered an unexpected token error in my code. This issue has happened to me before, but despite spending 2 hours trying to troubleshoot it, I couldn't find a solution. Below is a snippet of the problematic code. ...

My JavaScript code is functioning properly in jsfiddle, but when I try to run it on my own website, I encounter

Encountered an error message stating "Uncaught typeError: cannot call method 'hover' of null" following the line $('#nav li a').hover(function(){ in my JavaScript code. Check out the code on my site here: http://pastebin.com/GjZBEu3s Y ...

Using jQuery, create a variable that combines a text string with a

I have a list with custom bullet icons that I need help modifying using JavaScript. Specifically, I am looking for a script that can identify if the icon name is followed by a number and then add an image tag with a class based on that icon number for each ...

Verify if a user in discord.js has the necessary permissions

I need a special command that is restricted to users with the ban permission current code: if(msg.member.guild.me.hasPermission('BAN_MEMBERS')) { msg.channel.send("hi") } else { msg.channel.send("You do not have ...

What is the method for setting the doctype to HTML in JavaScript or React?

I created a canvas with a height equal to window.innerHeight, but unexpectedly it seems to have 100% screen height plus an extra 4 pixels coming from somewhere. I came across a solution suggesting that I need to declare doctype html, but I'm unsure ho ...

Preventing the mysql server called by php from running when the website is refreshed

My local website runs by querying a mysql database using inputs from an html form. The form values are passed to php via jQuery to execute the query. Is there a way to send a command to the mysql server to terminate the query if the web page is refreshed? ...

Mastering Data Labels in ng2-chart: A step-by-step guide

Once again, I find myself battling my Angular and JavaScript challenges, each question making me feel a little less intelligent. Let me walk you through how I got here. In my most recent project, I wanted to enhance the user experience by incorporating sl ...

When the JavaScript alert appears, play audio and then pause it when the alert is closed

I am attempting to have an audio play when a JavaScript alert is triggered and stop playing the audio when the user dismisses the alert. However, I am encountering an issue where the audio does not stop when the user closes the alert. Additionally, the a ...

When attempting to call Firebase Functions, ensure that Access-Control-Allow-Origin is set up correctly

Although it may seem straightforward, I am confused about how Firebase's functions are supposed to work. Is the main purpose of Firebase functions to enable me to execute functions on the server-side by making calls from client-side code? Whenever I t ...

Refreshing a JQuery select control to reload and re-render the options

I have implemented the following functions to enable searching within a select dropdown using an input text field: The first function triggers the search when a key is pressed in the input field: $( 'input#id_nit_del_cliente' ).keyup(function(e ...

We are sorry, but the request did not provide a full response. There seems to

I'm facing an issue with nodejs. When I make a request to an API using https.request, the response contains an object with 10,000 rows. However, the entire object does not arrive and when parsing it, I get the error: Unexpected end of JSON input. Is ...