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

Changing styles with the use of bootstrap.css themes on the fly

I'm experimenting with toggling between a custom dark and light theme in my MVC application. On the _Layout.cshtml page, the default theme is loaded by the following code: <link id="theme" rel="stylesheet" href="~/lib/bootstrap/dist/css/Original. ...

What is the method for including a class in the anchor element that is the closest sibling of the containing ul element in the HTML structure?

I'm currently exploring traversal in jQuery and I'm a bit confused about how the class is being added to all the items in the unordered list. I know it's probably something simple that I'm missing. Any assistance would be greatly apprec ...

Differentiating between an individual array and an array containing multiple arrays

Can jQuery differentiate between a regular array, an array of arrays, and an array of objects? var a = [1,2,3]; var a2 = [[12,'Smith',1],[13,'Jones',2]]; var a3 = [{val:'12', des:'Smith', num:1}]; //a = regular arr ...

How can I code a div to automatically scroll to the top of the page?

I'm attempting to implement something similar in WordPress - I want a div containing an advertisement to initially start 300px down the page, then scroll up with the page until it reaches the top, and finally stay there if the user continues to scroll ...

What is the best way to add Vue dependency using CDN?

For my project which is built using Kendo, Vue, .Net, Angular and jQuery, I need to incorporate https://www.npmjs.com/package/vue2-daterange-picker. <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-c ...

Is there a way to dynamically insert objects into an array from an ajax json request, in order to iterate through them later on?

I have a current code where I am trying to utilize data to create a new information window from the Google Maps API dynamically. Currently, I am pushing objects of different data types into an array, but I believe that might be the only issue here. How c ...

TabContainer - streamline your selection process with inline tabs

I am currently working on a GUI that includes a TabContainer with two tabs, each containing a different datagrid. I initially created the tabcontainer divs and datagrids declaratively in HTML for simplicity, but I am open to changing this approach if it wo ...

What are the best techniques for using jQuery to manipulate an HTML form that contains nested elements?

I have a scenario where I need to dynamically generate mini-forms within an empty form based on certain conditions. For instance, imagine a form that gathers information about restaurants such as their names and locations. Depending on the number of restau ...

The functionality of app.get('') is malfunctioning in Node.js when it comes to handling query parameters

I'm currently working on updating my conversation application to handle new routes that accept parameters and pass them along to the client side. However, I'm facing an issue with the .get() method not rendering the HTML as expected. 'use s ...

Enhancing TypeScript with Generic Proxyify Functionality

I'm attempting to enclose a basic interface provided through a type generic in order to alter the return value of each function within the interface. For instance: interface IBaseInterface { test(a?: boolean, b?: number): Promise<boolean>; ...

Double trouble: Knockout validation errors displayed twice

Currently, I am using the knockout validation plugin to validate a basic form field. The validation functionality is working as expected, however, it seems to be displaying the same error message twice under the text box. The code snippet that I am using ...

How can you display directions while using the Google Maps app in a React Native application?

I need assistance with rendering directions between two points (current location and a passed location). Currently, I am using Linking to open the Google Maps App. However, when clicking the button passing the (latitude, longitude), I want the map to disp ...

Incorporate 'Additional features' into the Navbar when adjusting window size

When the window is resized, I want to display a collapsed 'More options' button that will collapse all hidden <li> elements. Here is an example: <li id="menu_more_container" class="dropdown" style="display: none; ...

Utilizing a regular expression to target the characters [/ , .] within the ng-pattern validation

I am struggling to come up with a regex pattern that restricts input strings from containing forward slashes, commas, or dots. <form name="myForm"> <div class="col-sm-4"> <input class="form-control" type="text" dat ...

Can you provide guidance on displaying flash messages in my template using Express.js?

app.get('/',function(req,res){ res.render('home'); // Ensure the template has access to the flash message }); app.get('/go',function(req,res){ req.flash("info", "You have gone to GO and got redirected back home!"); ...

Having trouble running nodemon on my Windows 10 machine

Recently, I started diving into Node.js and managed to run my first node app successfully, albeit without using nodemon. To remedy this, I globally installed nodemon by running npm install -g nodemon, which went smoothly. However, upon executing nodemon in ...

What is the best way to switch from rows to cards in Bootstrap version 5.3?

In my current project, Next JS is the framework I am working with. I am faced with the challenge of creating a card layout that adapts based on device size - for smaller devices, I want a plain card with the image on top and text below, similar to Bootstra ...

Using AJAX to Access PHP Variables

I am working on creating a progress bar and have the following CSS code: #result{ background:#8c8f91; margin-left: 15px; margin-right: auto; table-layout: fixed; border-collapse: collapse; z-index: -1; position:relative; width: ...

Enhance communication system by optimizing MySQL, JavaScript, and PHP chat functionality

I have created a chat application using Javascript, PHP, and MySQL for two users. Every 3 seconds, it makes an AJAX request to a PHP file to retrieve messages from the database and update the page. Currently, the PHP query used is: SELECT * FROM tmessages ...

In React, what is the correct term for "selection boxes" when choosing multiple items in Finder?

I'm in search of a React component that allows me to select multiple elements on the screen by clicking, holding, and forming a square around them. I've tried searching for terms like 'selection box' and 'React select elements,&apo ...