two steps are required to answer your question:
- read console.log output into a variable
- saving the variable to a text file
step 1 - listen console logging events
it can by done by replacing the console object with self-made interface:
var consoleText = ""
// define a new console
window.console = (function(console){
return {
log: function(text){
console.log(text);
consoleText += text;
},
info: function (text) {
console.info(text);
consoleText += text;
},
warn: function (text) {
console.warn(text);
consoleText += text;
},
error: function (text) {
console.error(text);
consoleText += text;
}
};
}(window.console));
and for unhandled exceptions:
window.addEventListener('error', function(event) {
consoleText += event.message;
})
step 2 - save the log file
based on DevonTaig answer in Writing html form data to a txt file without the use of a webserver:
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
download("log.txt", consoleText)