'How to trigger "Save as Offline" Chrome Feature using JavaScript or onlick?
I have a simple html page, and want to give the visitors a button where, on clicking downloads the html or mhtml version of webpage. So, that users can view page offline.
I tried implementing "save as html" code but it messes up my js, css and html. However, chrome builtin, download button works cool.
How to trigger 'save offline' feature using button click? Or download the page as mhtml directly?
My visitors are ignorant students, so not everyone knows that feature exists on chrome. So, want to implement it on the page.
Solution 1:[1]
This code should work as long as the page is being served through a web server, rather than a file:// URL. The btn variable should be changed to whatever element you're using:
const btn = document.getElementById('download');
btn.addEventListener('click', async () => {
const resp = await fetch(location.href);
if (resp.ok) {
const blob = await resp.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = document.title;
link.click();
setTimeout(() => URL.revokeObjectURL(link.href), 7000);
} else {
alert('Error downloading webpage');
}
});
You can also hide the download button if the site is being viewed as a downloaded file with this code:
if (location.protocol == 'file:') {
btn.style.display = 'none';
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
