User:Elominius/One-click saver.js

From Wikiversity
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
function download(filename, text) {
  var tmp_node = document.createElement('a');
  tmp_node.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  tmp_node.setAttribute('download', filename);

  tmp_node.style.display = 'none';
  document.body.appendChild(tmp_node);

  tmp_node.click();

  document.body.removeChild(tmp_node);
}

function ISO8601_file_name() { 
	return new Date().toISOString().replace(":","-").replace(":","-");
}

function oneClickSave(include_title,comment) { 
    download(
		( document.title && include_title ? document.title + "." : "")
        + window.location.hostname 
        + "." 
        + ( comment != undefined  ? comment + "." : "" )
        // Avoiding colons for file system compatibilty and foregoing replaceAll() for browser compatibility.
        + ISO8601_file_name()
        + ".DOM.html"
        // Generates the file name.

        , "<!-- Downloaded on " + new Date().toISOString() + " from " + document.location.href + " using oneClickSave. Title: "+document.title+" -->\n"
        // Notes the source URL and time stamp inside the file.

        + new XMLSerializer().serializeToString(document)
        // Similar to document.documentElement.outerHTML, but includes text outside <html></html>.
    );
}
oneClickSave(true);