I have an html file that I would like to make available for offline use. This can be achieved easily by simply right clicking on the link on a desktop browser, then choosing "save as".
However, on a mobile device, I have tried using the download attribute on the anchor tag like so:
<a href="index.html" download>Download the page here.</a>
This seems to just take me to the page instead of downloading it.
My main goal is just to allow the user to download an html file to their mobile device.
There really isn't a right-click on mobile and holding down on the link shows a menu, but download isn't among them. The mobile browser itself may have a mechanism for saving a page once opened, but this would be sort of hard to walk the user through, and of course I'll have no idea what the mobile browser the user is using.
A special note here, the webpage I am trying to download does not have assets like images or style script files that need loaded in, all the assets are self-contained in the html file itself.
I actually came up with a solution to the problem, so I'll share it here, but I'm finding it hard to believe that there is not an easier way to do this.
My solution was essentially this, make an asynchronous request for the html file and read its text as a string. Then use that string to make a text blob and download it. Furthermore, to make sure the asset could be obtained from a local machine I served the data with a php file containing a header to ignore the cross origin restriction. (I didn't use fetch because I wanted to use settimeout).
To request an index.html
file from the location https://www.mypage.com/
:
Here is the downloader.php
file located in the base directory:
header('Access-Control-Allow-Origin: *');
?>
<?php include_once 'index.html';?>
The html file the user clicks:
<!DOCTYPE html>
<html>
<body>
<button onclick="downloadPageAsText('https://www.mypage.com/downloader.php', 'index', '.html');">Download</button>
</body>
</html>
The functions to allow downloading:
function downloadPageAsText(url, basename, suffix){
let xhttp = new XMLHttpRequest();
xhttp.timeout = 1000;
xhttp.ontimeout = function(e) {
alert("Request timed out. Try again later");
};
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
saveStringToTextFile(xhttp.responseText, basename, suffix);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function saveStringToTextFile(str1, basename = "myfile", fileType = ".txt") {
let filename = basename + fileType;
let blobVersionOfText = new Blob([str1], {
type: "text/plain"
});
let urlToBlob = window.URL.createObjectURL(blobVersionOfText);
let downloadLink = document.createElement("a");
downloadLink.style.display = "none";
downloadLink.download = filename;
downloadLink.href = urlToBlob;
document.body.appendChild(downloadLink);
downloadLink.click();
downloadLink.parentElement.removeChild(downloadLink);
}
Is there an easier way to allow the user to download an html file to their mobile device?