如何处理 Phonegap + JQM 应用程序中的链接?

How to handle links in Phonegap + JQM app?

我正在使用 Phonegap 和 jQuerymobile 构建一个应用程序。该应用大致是这样工作的:

1) 该应用程序从 public 服务器下载 ZIP 文件,然后将其解压缩到本地文件夹。我从 fileSystem.root.toNativeURL() 中获取了本地文件夹路径(在 OS 中,它是这样的:file://var/mobile/Container/Data/Application/xxxx/Documents/

2) 应用程序重定向到在本地文件夹中解压缩的 HTML(例如:file://var/mobile/Container/Data/Application/xxxx/Documents/index.html

我现在在 index.html 文件中遇到问题 b/c,所有链接都是绝对路径(例如:<a href="/content/index2.html">Link</a>)。这会破坏所有链接,因为(我假设)它们现在都指向 file://content/index2.html 而不是 file://var/mobile/Container/Data/Application/xxxx/Documents/content/index2.html.

我的问题是,我应该如何处理这些链接?我在想我应该重写所有链接以强制在其前面添加本地文件夹 URL。有没有更好的方法?

如果重写链接是可行的方法,我如何在 jQuery 移动设备上做到这一点?我在 jQuery 中执行此操作,这似乎有效 http://jsfiddle.net/jg4ouqc5/ 但此代码在我的应用程序(jQuery 移动)

中不起作用

删除链接开头的正斜杠。

href="content/index2.html">

您链接的示例应该有效,请确保您的 <base> 设置正确并且您使用正确的字符串进行替换。

是的,您必须在页面加载时规范化所有 URL。我现在无法使用 phonegap 进行测试,但您的 basePath 需要是以下之一:

  • 您在回答中描述的文件路径(不太可能)
  • window.location.origin(可选地包括 window.location.pathname

代码:

// mini dom ready - https://github.com/DesignByOnyx/mini-domready
(function(e,t,n){var r="attachEvent",i="addEventListener",s="DOMContentLoaded";if(!t[i])i=t[r]?(s="onreadystatechange")&&r:"";e[n]=function(r){/in/.test(t.readyState)?!i?setTimeout(function(){e[n](r)},9):t[i](s,r,false):r()}})
(window,document,"domReady");

domReady(function () {
    var anchors = document.getElementsByTagName['a'],
        basePath = /* get your base path here, without a trailing slash */;

    Array.prototype.forEach.call(anchors, function( anchor ){
        anchor.setAttribute('href', basePath + anchor.getAttribute('href'));
    });
});

当您加载 index.html 时,您将获得 file://some_path/..../index.html 作为您的基础 URL。现在将遇到的任何链接都可以根据基础 URL.

进行解析

你会更了解你的场景。可以通过多种方式解决此问题。

  • 与CMS/Code发电机签订合同。链接应该始终生成 Relative to the base URL 或 Absolute。您在页面中获得的链接是错误的 - <a href="/content/index2.html">Link</a> 理想情况下应该是 <a href="content/index2.html">Link</a> 或完全合格的 https://www.google.com.

  • 如果你想改变URL那么你可以在解压内容后使用本地代码来改变它。这将是非常简单的。

  • 如果你想在浏览器中更改 URL 那么你将不得不保留基础 url 然后处理几件事:

    a. absolute urls - 在你的情况下,你可以检查 window.location.protocol,如果它以 'http' 开头,然后跳过它。

    b.个子目录

这是我写的一个小东西: 注意:我没有尝试过此代码,您可能需要根据需要进行更改。

$(document).ready(function(){
        var base_file_name = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);

        //In index.html (persist this value in native)
        var baseUrl = window.location.href.replace(base_file_name, "");

        $("a").each(function () {
            this.href =  baseUrl + this.pathname;
            $(this).click(function (e) {
                e.preventDefault();
                alert(this.pathname);
                window.location.href = this.href;
            });
        });
    });