Skip to content

Instantly share code, notes, and snippets.

@crazytonyi
Last active April 6, 2019 11:14
Show Gist options
  • Save crazytonyi/c746c745a273ee1cd6ad to your computer and use it in GitHub Desktop.
Save crazytonyi/c746c745a273ee1cd6ad to your computer and use it in GitHub Desktop.
HTML Self-Replicating Script with Live textarea content
<!doctype html>
<html>
<!-- saveFile.html 1.0.0 2015 guest271314 edit, save `html` document -->
<!-- Created as proof-of-concept for SO question:
http://stackoverflow.com/questions/30563157/edit-save-self-modifying-html-document-format-generated-html-javascript
-->
<head>
</head>
<body>
<textarea></textarea>
<button>save file</button>
<script type="text/javascript">
var saveFile = document.getElementsByTagName("button")[0];
var input = document.getElementsByTagName("textarea")[0];
var a = document.createElement("a");
saveFile.onclick = function(e) {
var clone = document.cloneNode(true);
var doc_input = document.getElementsByTagName("textarea")[0];
var clone_input = clone.getElementsByTagName("textarea")[0];
clone_input.innerHTML = doc_input.value;
var doc_doctype = new XMLSerializer().serializeToString(document.doctype);
var clone_string = [doc_doctype + clone.documentElement.outerHTML];
var file = new Blob([clone_string], {"type":"text/html"});
a.href = URL.createObjectURL(file);
a.download = "file-" + new Date().getTime() + ".html";
a.click();
};
</script>
</body>
</html>
<!doctype html>
<html>
<!-- saveFile.html 1.0.0 2015 guest271314 edit, save `html` document -->
<head>
</head>
<body>
<textarea></textarea>
<button>save file</button>
<script type="text/javascript">
var saveFile = document.getElementsByTagName("button")[0];
var input = document.getElementsByTagName("textarea")[0];
var a = document.createElement("a");
saveFile.onclick = function(e) {
var clone = document.cloneNode(true);
var doc_input = document.getElementsByTagName("textarea")[0];
var clone_input = clone.getElementsByTagName("textarea")[0];
clone_input.innerHTML = doc_input.value;
var clone_string = [new XMLSerializer().serializeToString(clone)];
var file = new Blob([clone_string], {"type":"text/html"});
a.href = URL.createObjectURL(file);
a.download = "file-" + new Date().getTime() + ".html";
a.click();
};
</script>
</body>
</html>
@crazytonyi
Copy link
Author

@crazytonyi
Copy link
Author

savefileV2 replaces:

var clone_string = [doc_doctype + clone.documentElement.outerHTML];

with

var clone_string = [new XMLSerializer().serializeToString(clone)];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment