Search code examples
jquerygoogle-chrome-extensiongetjsoncontent-security-policy

Content Security Policy getJSON


I'm sorry for my english,

I have this following code in my HTML:

<script type="text/javascript" src="plugin.js"></script>

In my JS:

    $(document).ready(function() {
        $.getJSON("https://api.twitch.tv/kraken/streams/"+"NameOfStreamer"+"?callback=?",function(c) {

        if (c.stream == null) {
            $("p").text("Stream offline, n'hésitez pas à me rejoindre sur les réseaux sociaux afficher ci-dessous.");

        } else {

            $("p").text("Stream online, rejoins moi sur Domingo.tv en cliquant sur le lien ci dessous");

        }
    });
});

In my manifest :

{
  "manifest_version": 2,

  "name": "Getting started example",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },

  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/",
  ]
}

And i obtain that :

Refused to load the script 'https://api.twitch.tv/kraken/streams/NameOfStreamer?callback=jQuery11120590793181443587_1429560015317&_=1429560015318' because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

I would like to know how i can resolve that pls.


Solution

  • Your problem is in trying to use JSONP, which is not needed.

    You want to receive data, not a script to execute. JSONP is a trick to bypass the inability to make cross-domain requests if the remote server does not allow it; however, Chrome extensions have host permissions that bypass cross-domain restrictions.

    1. Add cross-domain permissions for the API you're using.

        "permissions": [
          "activeTab",
          "https://ajax.googleapis.com/*",
          "https://api.twitch.tv/*"
        ]
      
    2. Call the API without the callback parameter:

      $.getJSON("https://api.twitch.tv/kraken/streams/"+"NameOfStreamer", 
        function(c) {
          if (c.stream == null) {
            /*...*/
          }
        }
      );