Filling out a form within a webpage fetched through a DOMParser

Creating automation software in JavaScript using TamperMonkey.

The script performs several AJAX requests that retrieve HTML to be parsed with a DOMParser. Is there a way to submit these forms without opening the newly retrieved HTML on the main page?

Answer №1

Absolutely! The process involves retrieving the form from the document body, creating a FormData object with field values, and sending a POST request.

To simplify things, I utilized the Fetch API. You can learn more about it here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API. Additionally, I assumed that credentials are required to be sent from the same origin.

fetch('<GET URL>', {method: "GET", credentials: 'same-origin'})
  .then((response) => (response.text()))
  .then((responseBody) => {
    var html = parseHTML(responseBody);
    var form = html.querySelector('#my-form'); // Assuming this is the form ID
    var formData = new FormData();

    formData.append('someName', 'someValue'); // Field name should correspond to form fields

    postForm(formData)
      .then((response) => (response.text()))
      .then((responseBody) => {
        // Handle response from form submission here
    });
})

function parseHTML(string) {
  var doc = new DOMParser;
  return doc.parseFromString(string, 'text/html').body;
}

function postForm(formData) {
  return fetch('<POST URL>', {
    method: 'POST',
    body: formData,
    credentials: 'same-origin'
  })
}

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 can I dive into a nested array to access the properties of an object within?

My array, called sportPromise, is structured like this: 0: Array[0] 1: Array[1] 2: Array[2] 3: Array[3] When I run console.log(angular.toJson($scope.sportPromise, 'pretty'));, the output looks like this: [ [], [ { "id": 5932, ...

angular-bootstrap-mdindex.ts is not included in the compilation result

Upon deciding to incorporate Angular-Bootstrap into my project, I embarked on a quest to find a tutorial that would guide me through the download, installation, and setup process on my trusty Visual Studio Code. After some searching, I stumbled upon this h ...

"By selecting the image, you can initiate the submission of the form

I am trying to figure out why clicking on the image in my form is triggering the form submission by default. Can someone please provide guidance on this issue? <form name="test1" action="er" method="post" onsubmit="return validateForm()" <input ty ...

How can animations be disabled in Angular/Javascript?

I have been assigned the task of developing an Angular component for my company's applications that will include a toggle to disable all animations within the app for accessibility purposes. It is important to note that I am unable to go into each in ...

foreverjs neglects to log the child process's console.log output to any log files

I currently have a nodejs server running that fetches data using the setInterval function every x seconds. Here is a snippet of that part of the app: startPolling () { debug('Snmp poller started'); timers.setInterval( this.poll( ...

Contact a relaxation service periodically to pause its operation

To continuously check the status of a webservice, I need to make a REST call every x seconds (3000 ms) until the desired result is obtained or until it has been attempted 12 times. The call should also stop once the expected status is received: function m ...

Steps for embedding a font in a .pptx file

While working on creating a .pptx file using ASPOSE.Slides, I encountered some issues with embedding fonts. As an alternative option, I am looking for suggestions on how to embed custom fonts in a .pptx file using Apache POI or other methods. If you have ...

What is the best way to insert a chart into a div using *ngIf in Angular?

I just started using chart.js and successfully created the desired chart. However, when attempting to implement two tab buttons - one for displaying tables and the other for showing the chart - using *ngIf command, I encountered an error: Chart.js:9369 F ...

Converting a PHP variable to JSON in an AJAX call

At the moment, my approach involves using a jQuery Ajax asynchronous function to repeatedly request a PHP page until a large number of spreadsheet rows are processed. I am uncertain if the way I set the variables to be passed to the requested page is corre ...

Is there a bug in Safari 8.0 related to jQuery and backslashes?

I am using Mac OS 10.10 Yosemite and Safari 8.0. Attempting to read an XML (RSS) file: <content:encoded>bla bla bla</content:encoded> The Javascript Ajax method I am using is: description:$(valeur).find('content\\:encoded&apo ...

Using jQuery to enhance the functionality of the drop-down select feature

I am facing an issue with my index file code. When I select something from the drop-down menu, I expect to see a related dropdown appear. Although I have added this code to my file, I am unable to get the drop down to show after selecting the main type. ...

Running a Node Fetch POST call with a GraphQL query

I'm currently facing an issue while attempting to execute a POST request using a GraphQL query. The error message Must provide query string keeps appearing, even though the same request is functioning correctly in PostMan. This is how I have configur ...

The onChange function is not triggered when the dropdown menu consists of only one item

I am facing an issue with my dynamically populated dropdown menu. When the dropdown contains only one element, the onChange() function of my select tag does not work as expected. It functions perfectly fine when there are multiple elements present. How c ...

Registering components globally in Vue using the <script> tag allows for seamless integration

I'm currently diving into Vue and am interested in incorporating vue-tabs into my project. The guidelines for globally "installing" it are as follows: //in your app.js or a similar file // import Vue from 'vue'; // Already available imp ...

Incorporating an ASP.Net button through backend coding

I have a sleek form with an AJAX Accordion pane. I am using a Master page, but the ASPX child page is structured like this: <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"> <link rel="stylesheet" href="Content/theme ...

PHP Form encountering error due to JSON decoding following an AJAX request

After extensive research and much confusion, I have finally decided to seek help here. I am able to make my AJAX request post successfully in every format except JSON. I am eager to understand JSON so that I can start using it right away instead of learni ...

Include an Open OnClick event in the React/JSX script

We have a dynamic menu created using JavaScript (React/JSX) that opens on hover due to styling. My inquiries are: Instead of relying on CSS for the hover effect, where in the code can I implement an OnClick event to trigger the menu opening using Java ...

Safari and Chrome are directing Angular Http Post requests to different URLs

Using the Angular framework and the $http directive to make a post request to our API endpoint works fine in Chrome, but I'm encountering an issue in Safari. Below is the code snippet from my Api factory: assignments: function(csv) { var deferred = ...

Retrieve JSON Data Using Angular in a Wordpress Environment

I need assistance with displaying a JSON Array in <li>'s within a Wordpress Template. Here is the specific JSON file: I am completely unfamiliar with how to achieve this. This is the HTML code I have: <div ng-app="appExtern" ng- ...

Getting an input value dynamically in a React variable when there is a change in the input field

I am having an issue with my search text box. I need to extract the value onchange and send a request to an API, but when I try using the normal event.target method, it shows an error. How can I fix this? The problem is that onchange, I need to call a func ...