How to save html that has been modified in the browser (DOM) using Javascript / jQuery

First of all let me clarify that what I'm trying to do is for local use only, users will have direct access to the html page.

What I am trying to do is basically add and save text to an HTML file.

This is what I have.

HTML (index.html)

<div id="receiver"></div>
<button id="insertButton">Insert</button>

      

Js

$(document).ready( function() {
    $('#insertButton').click(function(){

        $('#receiver').append('<h1>Hi,</h1>','<p>How are you?</p>');
    })
});

      

I don't know how to save the file (index.html) after adding. Any idea how to do this? Is this possible with Javascript or jQuery?

+3


source to share


3 answers


You can change your handler to do this:

$(document).ready( function() {
    $('#insertButton').click(function(){

        $('#receiver').append('<h1>Hi,</h1>','<p>How are you?</p>');

        // Save the page HTML to a file that is automatically downloaded.

        // We make a Blob that contains the data to download.
        var file = new window.Blob([document.documentElement.innerHTML], { type: "text/html" });
        var URL = window.webkitURL || window.URL;

        // This is the URL that will download the data.
        var downloadUrl = URL.createObjectURL(file);

        var a = document.createElement("a");
        // This sets the file name.
        a.download = "source.htm";
        a.href = downloadUrl;

        // Actually perform the download.
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    })
});

      



You should take a look at the compatibility matrix and documentation URL

on MDN . Notably URL

not available for IE 9 or earlier. The same goes for Blob

.

+3


source


If I understand correctly, you need this on your local machine and for temporary use, you can store it in cookies. So whenever you load the page, check if a cookie is available, if yes then load data from cookies or load fresh data. You can use this data if and until the cookies are cleared.



Hope it helps ...

0


source


No javascript needed. After adding the html, just click Ctrl+Sto save the file locally with the modified html.

-1


source







All Articles