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

How to handle links in Phonegap + JQM app?

本文关键字:应用程序 JQM 链接 Phonegap 何处理 处理      更新时间:2023-09-26

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

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

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

我现在在索引.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。有没有更好的方法?

如果重写链接是要走的路,我如何使用jQuerymobile做到这一点?我在jQuery中做了这个,它似乎 http://jsfiddle.net/jg4ouqc5/工作,但这段代码在我的应用程序中不起作用(jQueryMobile)

当你加载index.html时,你会得到file://some_path/..../index.html作为你的基本URL。现在在自己的病房中遇到的任何链接都可以相对于基本URL进行解析。

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

  • 与CMS/代码生成器签订合同。链接应始终生成"相对于基本 URL"或"绝对"。您在页面中获得的链接是错误的 - <a href="/content/index2.html">Link</a>理想情况下它应该是<a href="content/index2.html">Link</a>或完全合格的,就像https://www.google.com一样。

  • 如果要更改URL,则可以在解压缩内容后使用本机代码进行更改。这将是非常直接的。

  • 如果要在浏览器中更改URL,则必须保留基本URL,然后处理几件事:

    a. 绝对网址 - 在您的情况下,您可以检查 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;
            });
        });
    });

您链接的示例应该有效,请确保您正确设置了<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'));
    });
});

删除链接开头的正斜杠。

href="content/index2.html">