如何以编程方式清除 javascript 控制台?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31261667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to clear the javascript console programmatically?
提问by Mediasoft
How we can clear the Console in Chrome, Firefox and other browsers. I've tried the following commands, but none is working:
我们如何在 Chrome、Firefox 和其他浏览器中清除控制台。我已经尝试了以下命令,但没有一个工作:
Chrome:clear()
铬合金:clear()
Firefox:console.clear()
火狐:console.clear()
Any ideas?
有任何想法吗?
回答by Govind Mantri
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
注意:在 Mac OS 的 Safari v9.1 和 Mac OS 的 Chrome v52.0 中成功测试(编辑后,08/2016)
回答by raydpratt007
In Firefox, as of July 25, 2019, I first tried typing:
在 Firefox 中,截至 2019 年 7 月 25 日,我首先尝试输入:
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.API
未定义。因此,闻到上面给出的答案可能是正确的,但不完全正确,我然后在控制台中输入了以下内容:
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.
这奏效了,控制台被清除并给出了控制台已被清除的消息。我不知道这是否适用于 Firefox 之外的任何其他浏览器,当然,我只知道它今天有效。
回答by Pedro Ferreira
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:
5 年后 ;-) 但如果它有任何用处,这里是 @govind-mantri 出色的答案,在TypeScript 中,避免了 TSLint 错误/提示:
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();
}