PhoneGap on iOS with absolute path URLs for assets?

tribalvibes picture tribalvibes · Jan 31, 2012 · Viewed 24.6k times · Source

Porting a web app to phoneGap on iOS, we have asset (and ajax) URLs that are absolute paths, e.g.:

<img src="/img/logo.png">

We have the img directory packaged under PhoneGap's www directory. The image will not load with the absolute path, but only with a relative path, e.g.:

<img src="img/logo.png">

Could someone please explain how the URL is being prefixed or translated in this context? I.e.:

<img src="/www/img/logo.png">

does not work either. So what is the URL base used by PhoneGap on iOS?

We've also tried, e.g.:

<img src="file://img/logo.png">
<img src="file:///img/logo.png">

but no go.

We would like to avoid changing the URLs to relative for the port, as absolute path URLs are used throughout the CSS, Ajax code, are set by Sprockets with the Rails backend, etc. How can we just get PhoneGap/UIWebView on iOS to load the assets using the absolute path URLs as written?

I see this question is asked a lot in various forms here on StackOverflow, but I've yet to see a correct answer.

Answer

Martin Zeitler picture Martin Zeitler · Nov 23, 2014

One can get the path to the application in JavaScript by:

cordova.file.applicationDirectory

Since I'm on Android, it says: "file:///android_asset/" ...for example:

var img_path = cordova.file.applicationDirectory + 'www/img/logo.png';

Like this all resources would be found when cross-building for various platforms.