How to open HTML files on a SDCard on an Android

Viewed 7598

I have a HTML file along with some images that I would wish to open on my Android phone. The reason is that I want to access that file even if I am offline. I have my HTML file on an external SD Card, so how can I open that file and use all the src="image.png" lines of code?

Can I use JavaScript to solve this problem?

4 Answers

Just tested it on my phone with a simple html file (text, link, image). And it should be enough if you just navigate to that .html file in your Android file manager and open it with the browser of your choice.

  1. Navigate to .html file using Android built in file manager
  2. Long press on the file until it is show as selected
  3. On your top bar, press the three dots ⋮
  4. In the menu that opens, press "open with"
  5. Now you can select which app you want to choose to open the file, select any browser

Afterwards your browser should open and display the rendered website, including images, styles etc. as long as they are at the correct place like defined in your .html file.

You'd need to rewrite all URLs, else this will result in HTTP 404...

another option would be to base64 encode and inline all the images.

Can you not use relative urls if all the images are in the same folder? If I open my html file, test.html, on my desktop, and I have the following element in it:

<img src = "./my-image1.png" />

and my-image1.png is in the same folder as my .html file, it will display.

The key is to include the ./.

As for javascript, you could use javascript to replace all your src attributes throughout your html file. Once you have all your images in the same folder as your .html, try something like this.

    <script>
        var imageTags = [...document.getElementsByTagName("img")];
        let regex = /([\w\d%]*\.(png|jpg|jpeg|gif))$/
        imageTags.forEach(element => {
            result = element.src.match(regex);
            element.src = "./"+result[0];
        });
    </script>

That way you don't have to go through and change all the tags yourself. Just add that script to the bottom of the page.

edit: reading some of the answers, some people are saying that SD cards store their files differently than regular directory paths, so my solution might be pointless. But I'm not sure. I think it's worth trying.

It worked for me on my local browser. Hope it works for you.

You need to change all image's URL to your Android/SD card directory.
Like this: Change src="image.jpg" to src="file:////storage/sdcard0/DCIM/image.jpg" **

**: May different for every Android phone. Check your file manager etc.

Related