Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right way of setting <a href=""> when it's a local file

Tags:

I'm trying to link to a local file. I've set href as follows:

<a href="file://C:/path/to/file/file.html">Link Anchor</a> 
  • In Firefox, when I right click and "open link in new tab", nothing happens.

  • When I right click and "copy link location", then manually open a new tab and paste the copied link, it works fine. So it seems my file:// syntax is fine. I've also tried it with 3 slashes like file:/// but it's the same result.

What am I doing wrong?

like image 201
sameold Avatar asked Aug 18 '12 19:08

sameold


2 Answers

By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)

So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).

If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,

like image 135
Jukka K. Korpela Avatar answered Sep 24 '22 18:09

Jukka K. Korpela


Organize your files in hierarchical directories and then just use relative paths.

Demo:

HTML (index.html)

<a href='inner/file.html'>link</a> 

Directory structure:

base/ base/index.html base/inner/file.html .... 
like image 25
Petar Sabev Avatar answered Sep 25 '22 18:09

Petar Sabev