Guide to using the Firefox WebExtensions API to make AJAX requests to the website of the current tab

I am trying to develop a web extension that will initiate an AJAX call to the website currently being viewed by the user. The specific endpoint I need to access on this website is located at /foo/bar?query=.

Am I facing any obstacles in using either the fetch API or an XMLHttpRequest to reach out to this endpoint?

Despite my attempts, I keep encountering a server error message when using these methods. Additionally, there is no activity showing up in the network tab while troubleshooting my extension. I have a suspicion that there may be a WebExtensions API designed for this particular task, but unfortunately, I have been unable to locate it.

Answer №1

Obtain a detailed description of the current tab that the user is viewing by using browser.tabs.getCurrent(). This description includes a property called url, which can be used to initiate an XMLHttpRequest.

browser.tabs.getCurrent().then(currentTab => {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", currentTab.url);
    // ...
});

Edit:
It has been highlighted by Makyen that tabs.currentTab is not the ideal method to use. Instead, utilize tabs.query along with active: true. The following code snippet should suffice:

browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
    let currentTab = tabs[0];
    let xhr = new XMLHttpRequest();
    xhr.open("GET", currentTab.url);
    // ...
})

To enable cross-origin requests, ensure that your manifest.json file grants permission as shown below:

{
  ...
  "permissions": [
    "tabs",
    "<all_urls>"
  ],
  ...
}

For example, adding <all_urls> will allow HTTP requests to any URL.

Further information can be found here.

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

reversed json using javascript

Is it possible to efficiently reverse the order of the following JSON object: { "10": "..." "11": "...", "12": "...", "13": "...", "14": "...", } so that it becomes: { "14": "...", "13": "...", "12": "...", "11": "... ...

What is the best way to save a webpage when a user clicks a button before leaving the page with Javascript

I've exhausted all my options in trying to find a way to trigger a button that saves the page upon exit, but it never seems to work. I need the event to occur even if the button is not visible at the time of the page exit. The new security protocols o ...

Accessing Struts2 tag attributes with JavaScript

Currently, I am using struts2 with jsp. Within the JSP file, there is a table with several rows of data. To display the row data in the table, iterators are being used. Each row includes a button that allows the user to update the row's data, such as ...

Create proper spacing for string formatting within an AngularJS modal

I am working with a popup that displays output as one string with spaces and newline characters. Each line is concatenated to the previous line, allowing for individual adjustments. Test1 : Success : 200 Test2 : Su ...

I'm unable to modify the text within my child component - what's the reason behind this limitation?

I created a Single File Component to display something, here is the code <template> <el-link type="primary" @click="test()" >{{this.contentShow}}</el-link> </template> <script lang="ts"> imp ...

Cropped portion of the captcha image located on the left side

edit: I manually adjusted cnv.width = this.width to 120 and it seems to be working. Upon closer inspection, I discovered that the image has both a rendered size and an intrinsic size. The width is 35 for rendered size and 40 for intrinsic size, which may e ...

JavaScript function unable to execute form action properly

I have a link RESET YEAR which triggers a servlet to check if the current year is equal to the present year. If they are not equal, then the function resetyear() is supposed to be called. The issue I am facing is that the function is not working as expecte ...

Transmit the Selected Options from the Checkbox Categories

Here's an intriguing situation for you. I've got a webpage that dynamically generates groups of checkboxes, and their names are unknown until they're created. These groups could be named anything from "type" to "profile", and there's a ...

How can we determine the remaining balance in the user's wallet after making purchases using JavaScript?

There are three arrays containing data from the back-end, with unknown names or products. The task is to calculate the total amount spent by the user and how much money is left in their wallet. In case the user runs out of money, they can take a loan which ...

Only incorporate the Angular service into the controller when it is necessary

When attempting to incorporate lazy loading for angular services, controllers, directives, and filters, I discovered a way to achieve something similar using RequireJS. However, I am struggling to find a way to dynamically load a service into a controller ...

Creating randomized sequences using JavaScript

One of my hobbies involves organizing an online ice hockey game league where teams from different conferences compete. It's important to me that every team gets an equal number of home and away matches throughout the season. To simplify this task, I&a ...

Troubleshooting in WebStorm: Uncovering the Root Cause Within an npm Package (node:36378) [DEP0005] - Warning: Deprecation Warning

Over the past 6 months, I've been encountering an error that seems to have surfaced after an update to node.js. (node:36378) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), ...

JavaScript Date behaving oddly

While working with Javascript, I encountered a puzzling issue involving the Date object. date1 = new Date(1970, 1, 1); date2 = new Date("1970-01-01T13:00:00.000Z"); console.log(date1.getYear()); //70 console.log(date1.getMonth()); //1 console.log(date1.g ...

Placing a user's username within an ejs template using express and node.js

Currently, I am attempting to integrate the username into a layout using ejs templating with node and express. Below are the steps I have taken: Mongodb model: const mongoose = require('mongoose') const Schema = mongoose.Schema; var uniqueValid ...

If the condition has a class name of condition, then display

Having performance issues due to slow data rendering with each tab using a partial view. The code snippet for each tab is as follows: <div class="tab-content" ng-controller="MyController"> <div id="tab-1" class="tab-pane fade active in " ng-i ...

Arranging a string array in JavaScript according to an integer array

Looking at the provided javascript arrays: letterArray ['a', 'e', 'i', 'o', 'u'] We also have another array that corresponds to it: valueArray [12, 22, 7, 7, 3] The goal is to sort the valueArray into: ...

Verify if the username is in use using an ajax request

Currently, I am in the process of verifying the existence of a username in the database while filling out a registration form using Ajax. This is the script I am using: $(document).ready(function() { //minimum characters required for username ...

Utilizing ExpressJS to save uploaded files using the FileReader object from the front-end

Despite researching multiple posts on this topic, I am still unable to successfully upload a file after numerous adjustments. My React form includes a PDF file upload component which looks like this: <Input onChange={(e) => this.handleFileUpload(e) ...

The main attribute in the NPM package.json is missing or has no appropriate entry

I'm really struggling to figure out the best approach for setting up my package.json file. I have a JavaScript module that contains multiple reusable JS files, let's call it Module1. In Module1's package.json, the name attribute is set to " ...

Incorporating a dynamic fill effect into an SVG pie chart

I am looking to animate a pie chart with a variable value that is unknown upon loading. Assuming I fetch the value promptly and convert it into a rounded percentage : var percentage = Math.round(sum * 100 / total); Next, I place this value here : <di ...