Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save html that was modified on the browser (the DOM) with Javascript/jQuery

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

What I'm trying to do is basically append 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>');
    })
});

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

like image 314
fs_tigre Avatar asked Nov 01 '22 14:11

fs_tigre


1 Answers

You could 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's 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 of URL over at MDN. Notably URL is not available for IE 9 or earlier. Same for Blob.

like image 53
Louis Avatar answered Nov 12 '22 16:11

Louis