Search code examples
androidcordovabrowsergetjson

$.getJSON not working with PhoneGap build


Grabbing json files from reddit, I've gotten this code to work in perfectly fine in Chrome:

function load(params){
    alert("test1")
    params = params || {};
    var container = $('#subreddit-content')
    $.getJSON("http://www.reddit.com/.json?jsonp=?", params, function(data){
        alert("test2")
        var children = data.data.children;
        $.each(data.data.children, function(i,item){
        ...
}
load();

However when I package it with PhoneGap no information gets populated, and only the first alert message was able to come through.

Searching for hours, the main solution people mention is whitelisting, since PhoneGap controls which URLS the app can access. I've tried whitelisting every possible thing with these in my config.xml file will still no luck:

<plugin name="cordova-plugin-whitelist" version="1"/>
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
<allow-navigation href="data:*" />
<access origin="*" />
<allow-intent href="*" />

Which was taken from here: https://github.com/apache/cordova-plugin-whitelist

I'm also running <preference name="phonegap-version" value="cli-5.2.0" /> if that makes any difference.

I'll love you forever whoever can help me with this. It's the only thing in my code that isn't working.


Solution

  • You will need to configure a Content Security Policy meta tag in your index.html document, to allow PhoneGap to reach www.reddit.com. Try something like this in the head of your index.html document:

    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; connect-src http://www.reddit.com">
    

    If working with iOS 9, you may also need to configure an App Transport Security exception in your -Info.plist file. You'd do that by adding this to that file:

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSExceptionDomains</key>
      <dict>
          <key>www.reddit.com</key>
          <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
      </dict>
    </dict>
    

    Newer versions of Cordova/Phonegap (5.4 on I think) will do that for you based on the whitelist settings in config.xml

    There's a detailed blog post here that covers how to configure Content Security Policy and App Transport Security.