How to clear the javascript console programmatically?
How we can clear the Console in Chrome, Firefox and other browsers. I've tried the following commands, but none is working:
Chrome: clear()
Firefox: console.clear()
Any ideas?
Solution 1:
For every browser it is different so you can write some script so that it will work for different browsers. or you can use this script
console.API;
if (typeof console._commandLineAPI !== 'undefined') {
console.API = console._commandLineAPI; //chrome
} else if (typeof console._inspectorCommandLineAPI !== 'undefined') {
console.API = console._inspectorCommandLineAPI; //Safari
} else if (typeof console.clear !== 'undefined') {
console.API = console;
}
console.API.clear();
so on for other browsers too.
Note: Successfully tested (after edit, 08/2016) in Safari v9.1 for Mac OS, and Chrome v52.0 for Mac OS
Solution 2:
In Firefox, as of July 25, 2019, I first tried typing:
console.API.clear();
But, that gave a message in the console that: console.API
is undefined.
So, smelling that something was probably right with the answer given above, but not exactly, I then typed the following in the console:
console.clear();
That worked, and the console was cleared and gave a message that the console had been cleared. I do not know if this would work in any other browser besides Firefox, and, of course, I only know that it worked today.
Solution 3:
Coming 5 years later ;-) but if it's of any use, here it is the @govind-mantri brilliant answer, in TypeScript, avoiding the TSLint errors/hints:
private clearConsole() {
// tslint:disable-next-line: variable-name
const _console: any = console;
// tslint:disable-next-line: no-string-literal
let consoleAPI: any = console['API'];
if (typeof _console._commandLineAPI !== 'undefined') { // Chrome
consoleAPI = _console._commandLineAPI;
} else if (typeof _console._inspectorCommandLineAPI !== 'undefined') { // Safari
consoleAPI = _console._inspectorCommandLineAPI;
} else if (typeof _console.clear !== 'undefined') { // rest
consoleAPI = _console;
}
consoleAPI.clear();
}
Solution 4:
console.clear();
- Using this in chrome console is clear but make sure preservelog is unchecked in console setting.