aboutsummaryrefslogtreecommitdiff
path: root/doc/tips/JavaScript_to_add_index.html_to_file:_links.mdwn
blob: 250bb26af4e998a3aeb842cfb7773cd19cca83a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
The source file `foo/bar.mdwn` or `foo/bar.html` generates the
page `foo/bar/index.html`, but the links to the page appear
as "`foo/bar/`".  This is fine (and recommended) for pages
served by an http server, but it doesn't work when browsing
the pages directly using `file:` URL.  The latter might be
desirable when testing pages before upload, or if you want to
read pages when off-line without access to a web server.

Here is a JavaScript "`onload`" script which fixes the URLs
if the `local.protocol` isn't `http` or `https`:

	function fixLinks() {
	  var scheme = location.protocol;
 	 if (scheme=="http:" || scheme=="https:") return;
 	 var links = document.getElementsByTagName("a");
	  for (var i = links.length; --i >= 0; ) {
 	   var link = links[i];
	    var href = link.href;
	    var hlen = href.length;
 	   if (hlen > 0 && link.protocol==scheme && href.charAt(hlen-1) == "/")
 	     links[i].href = href + "index.html";
	  }
	}

This can be placed in `page.tmpl`:

	<html>
	<head>
	<script language="JavaScript">
	function fixLinks() {
	...
	}
	</script>
	</head>
	<body onload="javascript:fixLinks();">
	...
	</html>

This script has not been extensively tested.

---

A version that handles anchors:


	function fixLinks() {
	  var scheme = location.protocol;
	  if (scheme != "file:") return;
	  var links = document.getElementsByTagName("a");
	  for (var i = links.length; --i >= 0; ) {
	    var link = links[i];
	    var href = link.href;
	    var anchor = "";
	    var anchorIndex = href.indexOf("#");
	    if (anchorIndex != -1) {
	      anchor = href.substring(anchorIndex);
	      href = href.substring(0, anchorIndex);
	    };
	    var hlen = href.length;
	    if (hlen > 0 && link.protocol==scheme && href.charAt(hlen-1) == "/")
	      links[i].href = href + "index.html" + anchor;
	  }
	}