Submitting a POST request using a Chrome Extension

I am in the process of developing a Chrome extension popup for logging into my server. The popup contains a simple form with fields for username, password, and a submit button.

<form>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
           placeholder="Enter email">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
  </div>
  <button type="submit" class="btn btn-primary btn-sm" id="loginButton">Log In</button>
</form>

To verify my server's response, I used the Insomnia REST client with the following details:

URL: https://myserver.com/login
Header:

Content-Type: application/x-www-form-urlencoded

Form URL Encoded:
email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89ece4e8e0e5c9ede6e4e8e0e7a7eae6e4">[email protected]</a> & password: password

In the Chrome extension, I created a script named signin.js to handle the button click event and send the request to the server.

// hardcoded for simplicity of this example
const email = <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d38303c34311d3932303c3433733e3230">[email protected]</a>
const pwd = password

var button = document.getElementById("loginButton");

button.addEventListener("click", function(){
    const req = new XMLHttpRequest();
    const baseUrl = "https://myserver.com/login";
    const urlParams = `email=${email}&password=${pwd}`;

    req.open("POST", baseUrl, true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.send(urlParams);

    req.onreadystatechange = function() { // Call a function when the state changes.
        if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
            console.log("Got response 200!");
        }
    }
});

In the manifest.json file, I specified the necessary permissions as follows:

"permissions": [
    "storage",
    "activeTab",
    "cookies",
    "*://*.myserver.com/*"
  ],

The extension is loading and running without any errors, but I am unable to view the request on the network tab in DevTools. Although all files are loaded successfully, there seems to be no request to myserver.com.
The requested URL appears as

Request URL: chrome-extension://ahlfehecmmmgbnpbfbokojepnogmajni/sign_in.html?

Answer №1

After thorough investigation, I discovered that the form was reloading the popup right after the submit button was pressed, causing it to refresh before I could view the request.
To resolve this issue, I had to prevent the automatic reload by adjusting my function like so:

button.addEventListener("click", function(e){
    e.preventDefault();

    const req = new XMLHttpRequest();
    const baseUrl = "https://myserver.com/login";
    const urlParams = `email=${email}&password=${pwd}`;

    req.open("POST", baseUrl, true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.send(urlParams);

    req.onreadystatechange = function() { // Call a function when the state changes.
        if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
            console.log("Got response 200!");
        }
    }
});

Now everything is functioning as intended.

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

"Assure that setTimeout will be executed within the then method in

Within an Immediately Invoked Function Expression (IFFE), I am returning a Promise. The first thing that is logged is first, followed by third, and then second. Despite having the setTimeout inside the then block, shouldn't everything within it be exe ...

What could be the reason for my button not updating its text using a method?

I attempted to change the inner text of the Edit button to Save after it's clicked using a method, but it doesn't seem to be working. I could really use some help with this. b-button.editbtn.d-flex.flex-row.mb-3(@click="editBlood") ...

Select preselected options in a multi-select dropdown using Knockout.js

I have a select multi that I've bound to a model, and now I want to select some values that were previously selected using a second model. It seems like a simple task, but in Knockout.js it's proving to be more complicated than expected. Here is ...

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Can you explain the distinction between "(.....);" and "{......}" within the context of React?

Encountering an error indicated in the image for the following code: handlechange(event) { this.setState (prevState => { return( checked : !prevState.checked );}); } Interestingly, changing the round brackets after "return" to curl ...

Reset dropdown selection when a search query is made

Currently experimenting with Angular to develop a proof of concept. Utilizing a functional plunker where selecting an option from a dropdown populates a list of items from an $http.get( ). Additionally, there is a search input that should trigger its own $ ...

Effortless form submission through Angular

When attempting to create a form submit using Angular $http, the following codes were utilized. HTML (within the controller div): <input type="text" name="job" ng-model="item.job"> <button type="submit" ng-click="post()">Add</button> J ...

Using destructuring assignment in a while loop is not functional

[a,b] = [b, a+b] is ineffective here as a and b are always set to 0 and 1. However, using a temporary variable to swap the values does work. function fibonacciSequence() { let [a, b, arr] = [0, 1, []] while (a <= 255) { arr.concat(a) [a, ...

Personalizing the pop-up window using window.open

When clicking a hyperlink on a page, I need to open multiple pop-up windows. To achieve this, I must use the Window.open function instead of showModalDialog. However, I have noticed that the appearance is not satisfactory when using Window.open. (Essentia ...

A technique for calculating the total quantity of each item individually while using v-for in VueJS

Struggling to code (complete newbie) using VueJS and facing a major roadblock. I have a list of orders and I need to sum the quantities of each item separately. The only way to access the items is through v-for. <tr> <td data-th="list"> < ...

React does not display the items enclosed within the map function

I am facing an issue with rendering elements from a map function. Despite trying to modify the return statement, I have not been able to resolve the issue. class API extends Component { myTop10Artists() { Api.getMyTopArtists(function (err, data) { ...

Firefox has trouble with jQuery AJAX as anchor tags in returned HTML are not clickable

The issue at hand: In Firefox, anchor tagged text in the returned HTML is not clickable (no "hand cursor" and no action), while IE 10 seems to handle it without any problems. The scenario: I am utilizing jQuery AJAX to request a PHP page that fetches HTML ...

Displaying minute scale from right to left using jQuery technology

I successfully created a minute scale that is functioning well, but now I am encountering an issue with displaying my scale. Instead of being oriented left to right, I would like it to be displayed from right to left. Can anyone suggest what might be wron ...

Clicking on the image in the Swiper Slider will update the URL

Hi there! I am looking for help with changing the image URL when clicked. Currently, I am using swiper for my image gallery. I want to change this URL: to If anyone has a solution or suggestion on how I can achieve this, please let me know! ...

A comprehensive guide to leveraging synchronous execution of setTimeout in JavaScript

Can the desired output shown below be obtained using setTimout? If it is possible, please provide your insight: console.log("1st"); setTimeout(() => { console.log("2nd"); },0); console.log("3rd"); The expected output should be: 1st 2nd 3rd ...

An error will be thrown if you try to pass an array attribute of an object as a prop to a React component

I'm trying to grasp why passing an array attribute of a data object into a Component as a prop is causing issues. Is this due to my understanding of how React functions, or are there potential pitfalls in this scenario? Any insight would be greatly ap ...

Creating a column for dates using the js-xlsx library

After multiple attempts using js-xlsx, I have encountered an issue when trying to write a XLSX file with a Date column. Whenever I open the file in Excel 2010, the date is displayed as the number of days from a specific origin rather than in the desired fo ...

Dealing with a frustrating roadblock in Three.js where you encounter an "Unknown format" error while trying to work with

Greetings, I am relatively new to THREE.js and currently experimenting with loading a .FBX Object using the FBXLoader found in three/examples/jsm/loaders/FBXLoader while integrating this into React.js. Upon launching the page, I encountered an issue where ...

Accessing a specific child div within a parent div using JavaScript and CSS

Struggling to target and modify the style of the child div within id="videoContainer" <div id="videoContainer"> <div style="width: 640px; height: 360px"> <------- this is the target <video src ...

Suggestions to reduce our website loading time

Query: How can one effectively reduce the file size of a webpage to improve loading speed? What specific optimization practices and coding techniques (in JavaScript and PHP) can be implemented to decrease page weight? Motivation: After reading an article ...