The GM_xmlHttpRequest POST method is not functioning properly when called within an event listener

My simple goal is to intercept xmlHttpRequests sent by a page and send them to my local server for logging in a text file. However, Ajax calls do not work in event listeners. I have tried various solutions all day long without success. Here is the code snippet:

var ajaxQueue = [];
var processAjaxQueue = function(){
  if (ajaxQueue.length > 0) {
    for (ajax in ajaxQueue) {
      var obj = ajaxQueue[ajax];
      setTimeOut(function(){GM_xmlhttpRequest(obj);},0);
    }
    ajaxQueue = [];
  }
}
setInterval(function(){
  processAjaxQueue();
}, 100);
function gmAjax(obj){
  ajaxQueue.push(obj);
}

function sendData(data)
{
                setTimeout(function() {gmAjax({
                    method: "POST",
                    url: "http://127.0.0.1/log/index.php",
                    data: "price="+data,
                    headers: {"Content-Type": "application/x-www-form-urlencoded"},
                    onload: function(response){alert('Loaded! '+response.responseText);}
                });}, 0);
}

(function(open) {
    XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
        this.addEventListener("readystatechange", function() {
            console.log(this.readyState);
            if(this.readyState == 4)
            {
                alert(this.responseText);
                sendData(this.responseText);
        }
        }, false);
        open.call(this, method, url, async, user, pass);
    };
})(XMLHttpRequest.prototype.open);

I am struggling to understand what the issue might be. The concept of gmAjax stems from a source where it was mentioned that greasemonkey scripts execute and stop abruptly, making it impossible to use addevent listener.

No errors are visible in the error console and the request works fine when not inside the event listener.

Any assistance would be highly appreciated. Thank you!

Answer №1

The initial concept is accurate. Nonetheless, there are a few enhancements to be made.

  • Include the @run-at document-start meta tag to ensure logging commences prior to any ajax requests being dispatched by the page.
  • It's essential to manipulate XMLHttpRequest within the actual window scope (unsafeWindow) instead of in the sandbox.

Hence, the modified code appears as follows:

// ==UserScript==
// @run-at document-start
// @grant unsafeWindow
// ==/UserScript==

var unsafe = unsafeWindow;

... // insert your code for managing the ajax queue here

var oldOpen = unsafe.XMLHttpRequest.prototype.open;

unsafe.XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
    this.addEventListener("readystatechange", function() {
        if(this.readyState == 4)
        {
            alert(this.responseText);
            sendData(this.responseText);
    }
    }, false);
    oldOpen.call(this, method, url, async, user, pass);
};

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

TroubTroubleshooting an Issue with Returning a View in ASP.Net Core When Using jQuery AJAX in

After returning a view from my controller and using jQuery to display the result, everything seems to work perfectly during debugging. However, when I publish it to the server, once the AJAX result is returned correctly, all elements on the page are someho ...

Update information with a fresh GET call - React Dropdown

I have implemented a Dropdown Menu using MUI that allows users to select a specific day value. I would like the menu to trigger a new GET request with the updated parameter whenever the selection changes. However, I am unsure how to achieve this since it u ...

Updating the Navigation Bar and Theme in CRM Dynamics 2013 to Reflect Your Organization's Branding

In my CRM Dynamics 2013 setup, I am faced with a unique challenge. I need to customize the Organization navigation bar based on which organization is currently loaded. Specifically, I have two organizations - QA and PROD. When a user switches to the QA org ...

Tips for effectively showcasing div elements

https://jsfiddle.net/qz8hL574/1/ for (var key in table) { if (table.hasOwnProperty(key)) { $('<div class="element"></div>').appendTo('#list'); document.getElementsByClassName("element")[key].innerHTML = ...

Capturing member function details using JSDoc

Here's the code snippet I'm working with: /** This class blah blah... @constructor **/ my.namespace.ClassA = function(type) { /** This function performs an action **/ this.doSomething = function(param){ } } The class will be inc ...

"Unable to locate the specified file or directory" error message pops up while attempting to save a file

Currently, I am in the process of generating a JSON file using my website with intentions to deploy it later. Below is the code snippet that I have implemented: saveFile = (i, data) => { var filename = `${i}_may.json`; var folder_list = ["desktop", ...

Changing the data request body in datatables ajax on button click

My goal is to initially fetch data when the page loads and then allow users to apply filters by clicking on them to fetch updated data. The query I am using is a POST request because it requires complex parameters that need to be formatted as JSON for bett ...

Javascript - formatting numbers with decimals

This question is not related to math or operators, but rather a formatting or masking issue. I am working on creating an order form that uses Javascript to tally and display the quantity and cost of each column in separate fields. I am trying to format th ...

Tips for refreshing the modified toggle in angular2

I currently have a newsletter subscription that is initially set based on the newsletter I receive when the user logs in. However, when I toggle the newsletter option, I receive a "successfully updated" message but the newsletter remains set to false even ...

A guide to managing AJAX requests within Symfony 2

I'm looking to remove a set of sessions on a page using AJAX. Essentially, I want users to be able to click on a link and have the session removed without having to navigate to a new page. Additionally, I would like to display a message upon successfu ...

Passing Variables from Node JS to Pug Template's HTML and JavaScript Sections

Here is a route that sends various variables to a Pug template: items.js route router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeExp ...

Strategies for including JavaScript variables in AJAX data

I have a basic webpage displaying employee names that can be dragged around using Jquery UI draggable. I am able to capture the "top" and "left" position of the dragged item and store it in a JavaScript variable. My next goal is to pass these two variable ...

There are two notable problems with Bootstrap 4 Tooltip. The first is that it appears when a button is clicked, and the second is that it shows up for disabled elements

I am currently experiencing an issue with my tooltip while using Bootstrap 4. In my index.html, I have the following script loaded: $('body').tooltip({ selector: '[data-toggle="tooltip"]', delay: { show: 550, hide: 0 } }); The proble ...

Converting a mongoDB response array from a JavaScript object to a JSON string: a step-by

After developing a custom javascript API to retrieve data from a MongoDB database, the issue arose where the data is being returned as an array of objects instead of a simple JSON string. The current statement used for retrieving the objects is: return db ...

Uh-oh: create-react-app installation has been canceled

As per the guidelines provided in Reactjs documentation: To start a new project, you must have Node version >= 8.10 and npm version >= 5.6 installed on your system. Use the following command to create a project: npx create-react-app my-app My envir ...

Passing data between the view and JavaScript in a Django application

Initially, I pass a JavaScript variable 'confirmed' to my Django view using a POST request. Then, a Python script processes this variable to perform certain actions. Finally, I aim to pass the processed data back to my HTML/JavaScript for display ...

Is it possible to connect a date range picker custom directive in AngularJS with the behavior of AngularUI-Select2?

I'm currently utilizing Angular UI - Select2 directive for displaying an option box. Bootstrap Date-Range Picker for showing a date picker Both functionalities work effectively on their own. Functionality of the Date picker Whenever there is a ch ...

Only the first column of a row in Flexbox will have a line break when exceeding the

Currently, I am utilizing flex with a row direction for a set of items with fixed widths causing overflow and a horizontal scrollbar, which is the desired outcome. Nevertheless, my requirement is for the first column in these rows to be full-width, while ...

When the collapsed navbar is displayed, elements are pushed beyond the boundaries of their parent container (Bootstrap 5)

Introduction Utilizing Bootstrap 5 (included with webpack 5), I am implementing the grid system and collapse function to design the homepage of this website, featuring 2 sidebars that collapse into a top bar. On mobile devices, the navigation collapses a ...

Asynchronous JavaScript combined with a for loop

I'm interested in accomplishing a straightforward task using Nodejs and Async. Let's say I have a total of pages, which is 4 in this example. I am looking to send a request 4 times and then execute a callback once all responses have been receive ...