Capture XMLHttpRequest request and manually send a 200 status response using vanilla JavaScript

After extensive research, I found conflicting information on this topic.
I need to intercept an XMLHttpRequest and simulate a 200 status response from the backend using plain Javascript. This is specifically for testing purposes.

So far, I have made progress:

const originalXHROpen = window.XMLHttpRequest.prototype.open;
const originalXHRSend = window.XMLHttpRequest.prototype.send;

window.XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
  this.interceptRequest = url.includes('foo/bar');
  originalXHROpen.apply(this, arguments);
};

window.XMLHttpRequest.prototype.send = function (data) {
  if (this.interceptRequest) {
    console.log('## INTERCEPTED REQUEST');
    // attempting to fake a 200 response
    return;
  }

  originalXHRSend.apply(this, arguments);
};

While I can successfully intercept the call, I have struggled to imitate the 200 status response. Is it actually feasible? If so, how can I accomplish it?

Thank you!

Answer №1

To modify the status retriever, follow a similar approach to how you customized other functions:

const originalXHRStatus = window.XMLHttpRequest.prototype.__lookupGetter__("status");
window.XMLHttpRequest.prototype.__defineGetter__("status", function() {
  if (this.interceptRequest) return 200;
  else return originalXHRStatus.apply(this, arguments);
});

Take note of the deprecation advisory for __lookupGetter__ and __defineGetter__. Although they are labeled as deprecated, I utilized these methods to align with your established modifications.

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

Switch up the box-shadow color with ColorThief!

Is there a way to adjust this script to change the box-shadow color of #player1? <script type="text/javascript> $(window).ready(function(){ var sourceImage = document.getElementById("art"); var colorThief = new ColorThief(); var color = ...

Effortlessly retrieving the id attribute from an HTML tag using jQuery

Currently, I am encountering an issue with a code snippet that is designed to extract the value from an HTML tag. While it successfully retrieves a single word like 'desk', it fails when attempting to do so for an ID consisting of two or more wor ...

Can you confirm if this is the most efficient method for loading google-analytics and jQuery?

It's not necessary for jQuery to be loaded immediately on page load: Here is what I currently have: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '...']); _gaq.pus ...

Issue with displaying custom in-line buttons in JQGrid

Currently, I am utilizing jqgrid 3.8.2 (I am aware it's not the latest version, but I plan on updating it soon after seeking some advice :-)) I have successfully incorporated a couple of in-line buttons into my jqgrid using the default formatter &apo ...

Issue encountered while sending binary data to the server

After attempting to read a local file on the client side and sending it to the server, I encountered an error while trying to retrieve the image. JavaScript let req let rsp async function _post(url,data) { req = await fetch(url,{method: 'POST' ...

Arranging by upcoming birthday dates

Creating a birthday reminder app has been my latest project, where I store names and birthdays in JSON format. My goal is to display the names sorted based on whose birthday is approaching next. Initially, I considered calculating the time until each pers ...

Iterate over a collection of JSON objects and dynamically populate a table with statistical data

In JavaScript, I am trying to dynamically generate a table with statistical data from an API that contains an array of JSON objects. The JSON data has a property called "score" which is interpreted as follows: score: 5 (excellent); score: 4 (very good); ...

The viewport width in NextJS does not extend across the entire screen on mobile devices

I'm currently tackling a challenge with my NextJS Website project. It's the first time this issue has arisen for me. Typically, I set the body width to 100% or 100vw and everything works smoothly. However, upon switching to a mobile device, I not ...

An async awaitCurrentBlock() function encountered an unexpected identifier while executing my JavaScript file

Encountering a problem while trying to execute my compile.js file using node compile.js. Here's my code: const async = require('asyncawait/async'); const await = require('asyncawait/await'); const HDWalletProvider = require(&apos ...

Error message: The variable "data" is not defined in next.js

Being new to React, I recently used getStaticprops to retrieve data from an API for a filter gallery project. However, I encountered an issue when trying to access the {props: data} outside of the blog function - it resulted in a Reference Error stating th ...

What is the best way to prevent automatic trimming in EJS variable assignment in Node.js?

When I attempt to write a variable from the database into an EJS table, it is being displayed with default trimming by the EJS template. However, I would like to display the variable from the database without any default trimming. I consulted the EJS temp ...

Using JavaScript to place image data on the canvas in an overlay fashion

I recently wrote the code below to generate a rectangle on a canvas: <!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canv ...

Unable to interact with buttons located in the title bar of the Electron application

I am currently working on developing a basic Text Editor using Electron. I am facing an issue with adding a custom title bar where the buttons are not clickable. To try and fix this issue, I have included an onclick tag to the buttons in my code. main.js ...

Is there a way to display a loader when an item is selected from a dropdown menu? For example, while data is being fetched from the backend, can we

This is the HTML form division I have created: <div class="col-lg-2 "> <select name="limitCount" id="limitCount" ng-model="limitCount" class="form-control col-md-2 panel-refresh" ...

What is the best way to programmatically disable a button in JavaScript or jQuery when all the checkboxes in a grid are either disabled or unchecked?

In my grid, one column contains checkboxes. I need to implement a feature where a button is disabled if all the checkboxes are unticked. How can I achieve this using JavaScript or jQuery? .Aspx File <asp:TemplateField HeaderText="Cancel SO Line Item"& ...

Dynamic RSS Aggregator

I'm interested in developing a simple application that can retrieve RSS feeds from any feed URL. Can anyone provide me with some basic guidance on how to accomplish this? I'm fairly new to AJAX and similar technologies, so any assistance would b ...

What causes Angular to consistently redirect to the homepage?

Whenever I attempt to access the '/' route, it consistently displays the static-root-component (the main page component). However, if I try to access the '/welcome' route, it immediately redirects back to '/' and loads the sta ...

The Vue.js application is experiencing issues with the v-for functionality

I am working on a Vue.js application where I am fetching a list using ajax: $.ajax({ method: 'POST', dataType: 'json', url: this.base_info.url + 'getavailability?token=' + this.token, data: this.search_inf ...

Learn how to eliminate all text characters from a string using jQuery, leaving only the numerical values behind

My webpage features a variety of different products, each with their own values. When trying to calculate the total sum of these products and display it in the shopping cart, I encountered an error displaying NaN. How can I remove this NaN from the strin ...

Adjust the JavaScript variable upon pressing the "c" key

I'm trying to figure out how I can toggle the value of variable x in JavaScript when the key "c" is pressed. Specifically, I want x to change from 0 to 1 when "c" is pressed and revert back to 0 when it's released. I have already defined and name ...