Friday, December 20, 2013

PhoneGap/Cordova: loading content from URL

 

Introduction

A colleague of mine and myself struggled recently about strange problem during development of mobile application by using PhoneGap framework.

The problem manifested in a strange behavior. Image couldn’t load content from specified URL. This actually manifested only on new versions of Android and was very strange for us since we double checked the image resource URL, which worked correctly within HTML in any browser.

var email = $.mobile.activePage.find('#txtEmail').val();
var urlGravatar = "http://www.gravatar.com/avatar/" + md5Calculator.md5(email);
$.mobile.activePage.find('#profileImageSection').html("<img id='profile_img' src='"+urlGravatar+"' />");

By using jquery mobile we wrote this code snippet which does the MD5 calculation over the entered email address and generates URL to Gravatar image. Next, we insert an image element inside our HTML page.


Solution


After spending a lot of time searching for a solution we finally found the source of the problem.


Inside PhoneGap’s   res/xml/config.xml   there is a special element that allows/disallows retrieving content from remote resources. Changing default value of localhost to allow all (i.e. *) sets the settings to allow retrieving content from any source.


<access origin="*" />


This way our image loaded successfully. If you want to be more specific, you can allow content on a certain domain as well:


<access origin=”http://google.com” />