What is the process for sending a request to an external site from a content_script in a web browser extension

I've been working on developing a Chrome extension with a feature that will display information from an external server, such as today's weather, in a popup within Gmail.

Methods attempted:

  1. Initially, I tried including the necessary JavaScript directly in the extension. However, making AJAX calls to my server violated the same-origin policy, rendering this method ineffective.
  2. Subsequently, I attempted to host the JavaScript file on the server and load it upon page load instead.

The content of my manifest.json file is as follows:

{
  "name": "cvnosnvsdionfois",
  "version": "0.1.0",
  "manifest_version": 2,
  "description": "sldnfksdngsdngods",
  "browser_action": {
    "default_icon": "images/icon.png"
  },
  "permissions": [
    "http://api.flickr.com/", "webRequest",
    "tabs", 
    "http://*localhost:8080*"
  ],
 "content_scripts": [
    {
      "matches": ["https://mail.google.com/*"],
      "js": ["http://localhost:8080/static/response.js"]
    }
  ]
}

It has come to my attention that content scripts cannot be sourced from an external URL, which suggests that this approach may not work. Therefore, I am seeking advice on the correct strategy. How can I implement JavaScript code that runs directly within Gmail and communicates with my server? For instance, how does Smartr handle this?

Answer №1

It's puzzling why Cross-Origin XMLHttpRequest didn't work, considering that Extensions have more freedom compared to regular web pages when it comes to using the XMLHttpRequest object. Regular web pages are bound by the same origin policy, limiting their ability to send and receive data from remote servers. On the other hand, extensions can communicate with remote servers outside of their own origin, provided they obtain cross-origin permissions first.

References:

Demonstration

This example code demonstrates the use of a background page to make XHR requests to another domain.

manifest.json

The manifest file is configured with all necessary permissions and a registered background page.

{
  "name": "Demo",
  "description": "Sample Message Communication",
  "version": "1",
  "permissions": [
    "<all_urls>"
   ],
  "background": {
    "scripts": ["background.js"]
  },

  "manifest_version": 2
}

background.js

This sample script sends a request to a random ASP page.

function makeXHR() {

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function (data) {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                  console.log("Response received successfully");
            }
        } else {
            //callback(null);
        }
    }

    var url = 'http://www.w3schools.com/html/default.asp';
    xhr.open('GET', url, true);
    xhr.send();

}
document.addEventListener("DOMContentLoaded", makeXHR);

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

AngularJS Error: [$injector:modulerr] - I'm new to this

I am not utilizing ngRoute or any Angular service that requires injection. I am injecting my own module and controller as necessary. However, I am still encountering the following error in the console: Uncaught Error: [$injector:modulerr] http://errors.an ...

What could be causing the jQuery Ajax call to fail on Azure?

I am facing an issue with my jQuery Ajax methods as they are not working on Azure. Interestingly, the code runs perfectly fine in my local environment but fails to function on Azure. Any thoughts on what could be causing this discrepancy? Check out my co ...

Is it possible for JavaScript to generate numerous functions using various other functions independently?

I currently have a substantial amount of code containing multiple event listeners on various HTML objects, all using the 'click' listener. However, I now realize that in addition to these click listeners, I also want mouseenter listeners on all o ...

Guide on transferring a variable from a Python settings.py file to a JavaScript file

Could someone help me with accessing a variable from the settings in Python? SESSION_COOKIE_AGE = 4500 I need to use this variable in a JavaScript (JS) code snippet. I came across an article that explains one method: However, I'm wondering if ther ...

Running a PHP function embedded in a JavaScript script

I've gone through all the questions here but I'm still struggling to grasp this concept or make it work. My goal is to have a button that triggers a script to execute a php function. HTML: <button id="update_submit" type="button" onClick="m ...

Modifying a variable in $rootScope data will also update other instances of $rootScope data

Since I need to use the data in multiple controllers, I have stored it in $rootScope.currentCache. When the page loads, the data typically looks like this: { System: "Foo Bar", StartDateTime: "2014-11-27T12:35:00" } (please disregard any formatti ...

The integration of Node.js and express.js from distinct JavaScript files

How can I utilize express.js to render html in two separate files? file1.js file2.js The code inside file1.js is as follows: var express = require('express'); var app = express(); app.get('/foo/bar1', (req, res) => res.json([&apo ...

Guidelines for properly storing user data post-login in Nuxt3

When a user logs in, I need to store their data for future use. I have middleware set up on the "/page" page to check if the user is logged in, and if so, it allows them through. However, I notice that the user data is lost when the page is refreshed. In t ...

Stretch background image with html2Canvas in Chrome

I am currently using html2canvas to generate an image of a canvas with a background. It is working fine in Firefox, but in Chrome, the background is being vertically stretched. I am unsure of what the issue may be. Here is the link to my fiddle: http://j ...

When a directive is passed a string with HTML tags, the tags are not displayed/rendered as expected

When it comes to passing a string with HTML content to my Angular directive, I've encountered an issue where the rendered output treats the HTML as text. While researching possible solutions, most of them seem to rely on using ng-bind-html directive, ...

Angular - Enhance ngFor index while filtering

I am currently working with a list that utilizes an *ngFor loop in the template: <li *ngFor="let product of products | filterProducts: selectedFilter; index as productId"> <a [routerLink]="['/product', productId]"> {{produc ...

The issue of continuous requests in AngularJS controllers

In my controller, I have a simple function that calculates the number of answers for each question: $scope.countAnswers = function(questionid) { AnswersQueries.getAnswers(questionid, function(answers) { var answersCount = answers.length; return ...

socket.io: Is there a way to dynamically invoke socket methods from an object in my code?

Presently, I am working with the following code block: io.sockets.on('connection', function(socket) { socket.on("action1", function(data){ socket.emit("action1", data); }); socket.on("action2", function(data){ socket. ...

Is there a way to make a try-catch block pause and wait for a response before moving

I've been successfully retrieving data from my Firestore database, but I've encountered a major issue that I can't seem to resolve... Whenever I click the "Read Data" button, I have to press it twice in order to see the console log of the d ...

How to locate the index.js file within my application using Node.js?

Directory Structure bin - main.js lib - javascript files... models - javascript files... node_modules - folders and files public - index.html route - javascript files... index.js package.json I am using Express and angular.js. The ser ...

What is the best way to establish a restriction on the number of items obtained from an RSS

I am receiving a feed from this specific link. My goal is to only retrieve the initial five items from the feed, but currently I am getting all of the items. Is there a way for me to specifically request only the first five items? Do I need to include an ...

Is it possible to have two unique keys in a single MongoDB schema?

Currently attempting to achieve this functionality using mongoose: const newContent = new Schema({ heading: { type: String, unique: true }, url: { type: String, unique: true }, //... }); However, an error is being thrown: MongoError: E11000 dupl ...

Obtaining the referring URL after being redirected from one webpage to another

I have multiple pages redirecting to dev.php using a PHP header. I am curious about the source of the redirection. <?php header(Location: dev.php); ?> I attempted to use <?php print "You entered using a link on ".$_SERVER["HTTP_REFERER"]; ?> ...

Exploring the magic of VueJS: Implementing computed properties for "set/get" functionalities in tandem with Vue.Draggable and

Currently, I am in need of assistance with utilizing "Vue.Draggable". For the past two days, I have been struggling to properly update the draggable array. The main challenge lies in: Updating the draggable array using computed set/get functions Obtaini ...

Refresh the text area with the latest information received from the servlet using JavaScript

I am currently working on a program that involves calling a JavaScript function with multiple requests to a servlet. My goal is to execute these requests one by one and receive a response after each execution. However, the function I have only displays the ...