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

How to automatically refresh a page in AngularJS after a POST request

After making a POST request, I attempted to use $state.reload in my controller to refresh the page. However, it is not updating the data on my page after registering the form. I have to manually refresh the page to see the correct data. .controller(' ...

What is the correct way to execute the query "select * from table where indexA >= 'a' order by indexB ASC limit 10" in indexedDB?

As I delve into learning about javascript IndexedDB, I have encountered a challenge in executing complex queries. My goal is to perform a select query like this one: "select * from table where indexA >= 'a' order by indexB ASC limit 10" I a ...

The task "gulp js src - duplication and implementation of base" involves duplicating

My gulp task is set up to copy JavaScript files. The initial setup below did not work: gulp.src('./**/*.js', {base: '../src/main/'}) .pipe(gulp.dest('../target/dist')); After making some adjustments, the following code ...

A feature in Rails allowing users to favorite posts using Ajax technology

Currently, I am working on displaying user posts with nested resources and have compiled a lengthy list of posts from various users. My goal is to allow users to click a small star icon next to each post in order to favorite it using ajax. Do you have any ...

What is the correct way to securely send the username and password from a ReactJS frontend to the backend for authentication?

My React application includes an onChange function on a form that collects username and password. Upon submission, the username and password are sent to the server side using redux dispatch in Node.js. On the server side, I am authenticating the credentia ...

Tabulator automatically inserted 'numrow' after retrieving the data

I have a table of undetermined information (consisting of various columns and rows). I am now at the point where I need to utilize the function table.updateData(), but this function specifically requires the column id to be present in the data structure. S ...

Angular 4: Modifying the URL without the Component being Displayed

I'm currently facing an issue where I am attempting to link a component from one component using routerLink = "selected" const routes: Routes = [ { path: '', children: [ { path: 'account&apo ...

The point in the vector data is incorrectly positioned on the map in OpenLayers

I am looking to display a world map using the default OpenLayers WMS, along with a single point on it that will have interactive events like onhover. Below is my code snippet: var options = { projection: ...

Using the spread operator in ES6 allows for arguments to be placed in a non-con

When working in nodeJS, my code looks like this: path = 'public/MIN-1234'; path = path.split('/'); return path.join( process.cwd(), ...path); I was expecting to get: c:\CODE\public/MIN-1234 but instead, I got: `‌publ ...

Adding content to a text field and then moving to the next line

I am looking to add a string to a text area, followed by a new line. After conducting some research, here are the methods I have attempted so far but without success: function appendString(str){ document.getElementById('output').value += st ...

Having difficulty executing the Cypress open command within a Next.js project that uses Typescript

I'm having trouble running cypress open in my Next.js project with Typescript. When I run the command, I encounter the following issues: % npm run cypress:open > [email protected] cypress:open > cypress open DevTools listening on ws: ...

Utilizing the controller specified in the template that has been included

Within this snippet of code, I am attempting to utilize a controller named FooCtrl that is defined in the included template app/foo.html, using the directive common.script. angular.module('common.script', []).directive('script', func ...

What is the best way to eliminate the default hover effect using the MenuItem Mui class?

My goal is to eliminate the default gray hover over animation when using the MUI menu item class. I have attempted several methods, but none have been successful so far. Here are a couple of examples: <MenuItem divider sx={{'&:hover':{bac ...

Error will be thrown if the initialDueDate parameter is deemed invalid in Javascript

Can someone help me improve the calculateNextDueDate function which takes an initialDueDate and an interval to return the next due date? I want to add argument validation to this function. Any suggestions would be greatly appreciated. Thank you! const I ...

Updating a value in Expressjs variable is not working as expected

In the code snippet below, I have declared a variable called sumOfRevenue. I assigned it a value of 10 in the router, but when I try to print its value, it comes out blank. Can you please help me understand why it's not showing as 10? Please review t ...

The concept of an HTML pop-up message that hovers above the content

While working on my HTML form, I encountered an issue regarding the display of a warning message notifying users about the caps lock being on. Currently, the warning is shown correctly in a div located to the right of the text box. However, this div's ...

I must add and display a tab for permissions

I am currently using the material UI tab for my project. My goal is to display the tab only when the permission is set to true. I have successfully achieved this functionality, but the issue arises when the permission is false. It results in an error that ...

A "Uncaught TypeError" error occurs when trying to execute a function using the dollar sign

After successfully recognizing the hover function, the console displays an error message: Uncaught TypeError: $ is not a function <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> $(docume ...

Difficulty encountered when trying to update intricate model using Angular UI modal

My current project involves managing a model containing nested arrays that represent different sections of a floor plan. Each section contains an array of booth objects. To optimize user interaction, I've created a view that displays all the booths on ...

Which is better for posting data via ajax: using JSON.stringify() or default URL encoding?

Is there a specific advantage to using JSON.stringify() when posting a complex object compared to allowing default url encoding with jQuery.ajax? The MVC WebApi I am utilizing is able to handle both types of requests without any issues, so the need to send ...