Loading Google API Javascript Client Library into Chrome Extension

woojoo666 picture woojoo666 · Sep 8, 2013 · Viewed 14.9k times · Source

I've been trying to wed the google api javascript client library with a chrome extension for a while now, but it seems the chrome extension has a terrible case of cold feet. The link to the script is

https://apis.google.com/js/client.js

Downloading the files is messy because the script actually loads other scripts. I've tried including it in the manifest

manifest.json (excerpt)

"background": {
  "scripts": [
    "background.js",
    "https://apis.google.com/js/client.js?onload=callbackFunction"
  ]
},

but then the extension doesn't load. I've also tried injecting the script into the background html

background.js (excerpt)

 var body = document.getElementsByTagName('body')[0];
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = "https://apis.google.com/js/client.js?onload=callbackFunction";

 body.appendChild(script);

but the chrome debugger gives me

Refused to load the script 'https://apis.google.com/js/client.js' because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

Any ideas, or are they fated to be kept apart?

Edit: note that you must add "?onload=myCallbackFunction" to the script url if you want to utilize a callback function. Thanks Ilya. More info here

Answer

woojoo666 picture woojoo666 · Sep 8, 2013

So far the only solution I've found is to first inject the script into the background html page like I did:

background.js (excerpt)

 var head = document.getElementsByTagName('head')[0];
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = "https://apis.google.com/js/client.js?onload=callbackFunction";
 head.appendChild(script);

And then to bypass the security warning, edit the manifest file (source):

manifest.json (excerpt)

"content_security_policy": "script-src 'self' https://apis.google.com; object-src 'self'"

However, note that bypassing the security only works for https links, and I also find it kind of hacky...any other solutions are welcome