PhoneGap on iOS with absolute path URLs for assets?

假如想象 提交于 2019-11-27 21:08:51

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.

Did some testing and maybe a bit of JavaScript hackery can make it a bit more manageable. This will change all <a> and <img> tags with URL starting with / to be relative to the current file.

Put this into a file and include it with a <script> tag or inject it with stringByEvaluatingJavaScriptFromString:

document.addEventListener("DOMContentLoaded", function() {
  var dummy = document.createElement("a");
  dummy.setAttribute("href", ".");
  var baseURL = dummy.href;
  var absRE = /^\/(.*)$/;

  var images = document.getElementsByTagName("img");
  for (var i =  0; i < images.length; i++) {
    var img = images[i];
    var groups = absRE.exec(img.getAttribute("src"));
    if (groups == null) {
      continue;
    }

    img.src = baseURL + groups[1];
  }

  var links = document.getElementsByTagName("a");
  for (var i =  0; i < links.length; i++) {
    var link = links[i];
    var groups = absRE.exec(link.getAttribute("href"));
    if (groups == null) {
      continue;
    }

    link.href = baseURL + groups[1];
  }
});

When checking the absolute path through your iPhone/iPad you would see something like this:

<img src="file:///var/mobile/Applications/7D6D107B-D9DC-479B-9E22-4847F0CA0C40/YourApplication.app/www/logo.png" />

And it will be different on Android or Windows devices so I don't think it's actually a good idea to reference assets using absolute paths in this case.

As an alternative you could consider using the base64 strings in your CSS files:

div#overview
{
    background-image: url('data:image/jpeg;base64, <IMAGE_DATA>');
    background-repeat: no-repeat;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!