简体   繁体   中英

How do I make a request to an external site from a content_script

I am trying to make a chrome extension that will display a popup in my Gmail that will contain some information from my external server, say today's weather.

What I have tried

  1. I have tried including the js in the chrome extension, but then trying to make an AJAX call to my server violates the same-origin policy. So that option didn't work.
  2. So then I tried keeping my js file on the server and loading it on page load.

My manifest.json looks like this:

{
  "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"]
    }
  ]
}

I have read elsewhere that Content scripts cannot be included from an external URL, so I figure that this will not work. What is the right approach here. How can I have some javascript code that runs in Gmail, that can request information from my server? For example, how does Smartr do it?

I ain't sure why Cross-Origin XMLHttpRequest did not work because Extensions aren't so limited like Regular web pages that can use the XMLHttpRequest object to send and receive data from remote servers and are limited by the same origin policy . An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.

References:

Demonstration

This sample code uses background page to make XHR for another domain.

manifest.json

I ensure manifest has all permissions available and also registered a background page.

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

  "manifest_version": 2
}

background.js

This sample code make a request for some random asp page

function makeXHR() {

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM