1

I am trying to access data from a website in my Chrome extension background page. However, I keep getting an error.

I packed the extension and installed it by drag-n-drop into chrome://extensions. It does ask me for permission to view all websites.

Manifest:

"permissions": ["webNavigation", "tabs", "*://*/*", "http://www.google.com/"],

Background.js:

chrome.browserAction.onClicked.addListener(function(tab) {

    var xhr = new XMLHttpRequest();
    xhr.open('GET', "http://www.google.com", true);
    xhr.send();

}

Errors

Refused to connect to 'http://www.google.com/' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

Error in event handler for browserAction.onClicked: SecurityError: Failed to execute 'open' on 'XMLHttpRequest': Refused to connect to 'http://www.google.com/' because it violates the document's Content Security Policy.

user984003
  • 28,050
  • 64
  • 189
  • 285

1 Answers1

3

Those two errors happen respectively because you're trying to make a request to a page without asking for the relative permissions, which have to be set in the "content_security_policy" (CSP) field of your extension's manifest, and because you're trying to connect to an insecure source: you need to GET the page over https:// if you want to make it work, otherwise Chrome will reject your request.

Your CSP field in the manifest should look something like this:

"content_security_policy": "default-src 'self' https://google.com"

See specific information about the CSP at the Chrome extension developer guide here and in the W3C documentation here.


Anyway, even configuring the right CSP and loading over https, Google still doesn't let you make XMLHttpRequests to some of their pages (like the main page, which is the one you're trying to access) nor load them inside an <iframe>, so even doing all right, the request will be blocked on the server side, producing the following error in JavaScript:

Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://google.com/'.

Stated the above, since that it isn't possible to load/request https://www.google.com/ directly, you just have to abandon any script you wish to create which involves doing so.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128