A support widget lets a user send a bug report, and the most useful thing to attach is what the page logged just before things went wrong. To get it, the page wrapsconsole.log: a new function records each call and then hands it to the original, so the developer console still shows everything.
Write recordConsoleLog() in console-history.js. It starts recording at once and returns an object to read and end the record.
functionrecordConsoleLog() // returns { history, clear, stop }history() // returns an array: one array of arguments per call, oldest firstclear() // forgets the recorded calls; recording goes onstop() // stops recording and puts the previous console.log back
Every console.log call after recordConsoleLog() is recorded as the array of its arguments, oldest first. A call with no arguments is recorded as []. Calls made before are not recorded.
Each call still reaches the console.log that was there before, with the same arguments and with this unchanged, and the wrapper returns what it returns.
Values are recorded as they were passed: an object is kept, not copied.
history() returns a copy: changing the returned arrays never changes the record.
clear() empties the record and recording continues.
stop() ends recording and puts back the exact function that was there before. The record stays readable.
stop() never removes a function installed after this recorder: when console.log is no longer this recorder's function, stop() only ends the recording. Calling stop() twice is harmless.
Two recorders can run at once: both record each call, and the message is printed once.
constrecorder=recordConsoleLog();constcopy= recorder.history();copy.push(["fake"]);recorder.history(); // [] : the record is not changed
JAVASCRIPT
consta=recordConsoleLog();constb=recordConsoleLog(); // b wraps a's functiona.stop(); // console.log is b's function, so a only stops recordingconsole.log("x"); // recorded by b only, printed once