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

Prevent MUI Autocomplete from closing when the option menu is opened with blur

Seeking assistance with modifying an autocomplete menu to include a dropdown for each item. Issue arises after trying to open the additional menu as it triggers an immediate closure of the autocomplete. For reference, attached is an image showcasing the i ...

Verify the functionality of the input fields by examining all 6 of them

I'm facing a challenge with a validation function in my project that involves 6 input fields each with different answers. The inputs are labeled as input1 to input6 and I need to verify the answers which are: 2, 3, 2, 2, 4, and 4 respectively. For e ...

Struggling to make GET requests in REACTjs without using Redux

We are currently in the process of developing a React application without using Redux, but instead utilizing Webpack. Our app uses Axios to send a GET request to the server. While the server does receive the request and we can see our console.log statement ...

The installation of AngularJS libraries via npm was unsuccessful

After installing mean.io and running sudo npm install, I followed the commands in sequence: sudo npm install -g meanio mean init yourNewApp cd yourNewApp sudo npm install -g bower sudo npm install The process was supposed to download and install AngularJ ...

Type Error: Issue encountered while resolving module specifier

Upon trying to import the d3.js library in a project that utilizes npm, I encountered the error message: TypeError: Error resolving module specifier: d3. This issue specifically occurred while using Firefox. index.html <!DOCTYPE html> <html lang ...

JavaScript function unable to access static file for image

I need assistance with dynamically displaying an image (a checkmark or "X") based on a variable. When I insert the image using a script directly in the HTML file, it functions correctly. However, when attempting to set the image from within the createEasyD ...

Trigger function in a different child component on mouse up

Trying to call a function in a child component from another child component in ReactJS. Specifically, I want to trigger a function in another component when the 'mouseup' event happens. Here is an illustration of what I am attempting to achieve: ...

Conceal a div and label after a delay of 5 seconds with a JavaScript/jQuery function in C#

Here is a sample div: <div class="alert alert-success alert-dismissable" runat="server" visible="false" id="lblmsgid"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

JavaScript Navigation Bar Error: The value of 'undefined' is not recognized as an object

Having just started learning HTML, CSS, and JavaScript, I encountered an error message that reads: TypeError: 'undefined' is not an object. Despite my best efforts to troubleshoot the issue, I have been unable to resolve it. Is there anyone who c ...

What is the best way to extract words from a string within a textarea using javascript?

Currently, I am focused on improving my skills in JavaScript and HTML. In one of my projects, there is a text area where the user inputs a CSV format like this: 17845 hello bye 789 After input, I get 17845,hello,bye,789. Now, the challenge is t ...

Avoiding jQuery selector

What is the reason for the selector working in the first example but failing in the second one? Check out jsfiddle. <div id="hello[1][2]_world">&nbsp;</div> <textarea id="console"></textarea> <script> $(document).re ...

Steps to load data using ajax-php with specific parameters

I have a situation where I need to trigger a JavaScript function when a link is clicked. <input type='hidden' id='name'> <a href='#' onclick='getUsers(1)'>Click here</a> function getUsers(id){ $( ...

Guide on navigating through various HTML pages with distinct parameters using Node.js (Express server)

Seeking assistance with a Node.js server that receives an ID as a query parameter. Each time a client connects with different parameters, I aim to serve them a unique HTML page containing a simple UI with 2 dynamic arrays. Everything seems to be working co ...

Adding dynamic elements to a pop-up window with the use of jQuery's .load() function

When implementing Javascript to create a modal, I have encountered an issue where the close button disappears. The modal opens and loads different HTML files dynamically using the jQuery load() method, but the close button vanishes. I suspect that the mod ...

Eliminate the registration message from TinyMCE by importing a package

Looking to create a TinyMCE React package, I've been using import { Editor } from '@tinymce/tinymce-react'; However, I'm encountering this message - To remove the message, typically you would add the API key to the .js. in your <scr ...

Customizing Axios actions in Vue JS using a variable

I have a form in my Vue component that sends a reservation object to my API for storage. I am exploring the possibility of setting the axios action dynamically based on a variable's value, without duplicating the entire axios function (as both the pos ...

Execute a PHP script to modify a section of a PHP file

I successfully implemented a piece of code into a PHP file by manually searching for the right section and inserting it. Now, I am looking to automate this process with an install script for my code. The ideal installation script would: 1. Copy the exist ...

How can you style a two-item list in Material-UI React to display the items side by side?

I have a list that contains two items: 'label' and 'value'. This is the current layout: https://i.stack.imgur.com/HufX7.png How can I rearrange the items on the right to be positioned next to the label on the left? https://i.stack.im ...

Interactive image sliders in a Netflix-inspired style with live previews on hover, fully compatible with Bootstrap framework

I'm looking for suggestions on Twitter Bootstrap compatible jquery plugins that can create a Netflix-style continuously scrolling image carousel with mouse-over functionality. I've tried the carousel included in the Bootstrap JS library, but it r ...