[SOLVED] How to trigger "Save as Offline" Chrome Feature using JavaScript or onlick?

Issue

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

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');
    }
});

This works by first fetch()ing the current page’s contents, then creating an object URL of the result. Then it creates a hidden <a> tag whose .href is set to the object URL, so when the <a>. tag is clicked, the object URL will be downloaded. I also set the .download property, which specifies the filename of the downloaded file, to the current page’s title. Finally, the hidden <a> tag is clicked and the object is revoked to cleanup memory.

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';
}

Answered By – Michael M.

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *