<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JavaScript to add index.html to file: links</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="../style.css" type="text/css" /> <link rel="stylesheet" href="../local.css" type="text/css" /> </head> <body> <div class="page"> <div class="pageheader"> <div class="header"> <span> <span class="parentlinks"> <a href="../index.html">ikiwiki</a>/ <a href="../tips.html">tips</a>/ </span> <span class="title"> JavaScript to add index.html to file: links </span> </span> </div> </div> <div id="pagebody"> <div id="content" role="main"> <p>The source file <code>foo/bar.mdwn</code> or <code>foo/bar.html</code> generates the page <code>foo/bar/index.html</code>, but the links to the page appear as "<code>foo/bar/</code>". This is fine (and recommended) for pages served by an http server, but it doesn't work when browsing the pages directly using <code>file:</code> 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.</p> <p>Here is a JavaScript "<code>onload</code>" script which fixes the URLs if the <code>local.protocol</code> isn't <code>http</code> or <code>https</code>:</p> <pre><code>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"; } } </code></pre> <p>This can be placed in <code>page.tmpl</code>:</p> <pre><code><html> <head> <script language="JavaScript"> function fixLinks() { ... } </script> </head> <body onload="javascript:fixLinks();"> ... </html> </code></pre> <p>This script has not been extensively tested.</p> <hr /> <p>A version that handles anchors:</p> <pre><code>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; } } </code></pre> </div> </div> <div id="footer" class="pagefooter" role="contentinfo"> <div id="pageinfo"> <div class="pagedate"> Last edited <span class="date">Tue Feb 26 23:01:54 2019</span> <!-- Created <span class="date">Mon Sep 10 04:32:55 2007</span> --> </div> </div> <!-- from ikiwiki --> </div> </div> </body> </html>