[英]Detect a console.warn message
我需要找出警告(不是錯誤)消息何時發送到瀏覽器的 console.log 。 從研究中,我知道我可以使用類似於以下的 JavaScript 代碼檢測錯誤消息:
window.onerror = function(errorMsg, url, lineNumber){
// any action you want goes here
// errorMsg is the error message itself.
// url should be the file presenting the error, though i have
// found that it only presents to me the address of the site.
// lineNumber is the line number the error occoured on.
// here is an example of what you could do with it:
alert("Error in " + url + " at " + lineNumber + ":\n" + errorMsg);
}
但這僅顯示錯誤消息。 它不會顯示任何警告消息。
是否有類似的方法來檢測 console.log 中的特定警告消息? 或者,是否有一些 JS 代碼可以讓我在 console.log 中搜索特定字符串?
請注意,我可以在瀏覽器的調試(控制台日志記錄)窗口中看到警告消息。 但是我想“攔截”警告消息並在發現該警告時執行一些操作。
添加
目的是找出特定警告消息何時發生; 該消息類似於"Loading failed for the <script> with source "https://www.example.com/js/somescript.js" .
但是如何攔截瀏覽器輸出的警告消息(不是錯誤;我包含的代碼就是這樣做的)的問題(不是我的代碼)。
添加
所以,這就是我需要的。 假設這個代碼
console.warn("Here is a warning!");
您會編寫什么代碼來查看該消息是否作為警告寫入控制台?
覆蓋console.log()
怎么樣?
let tmpConsoleLog = console.log; console.log = function(msg){ // Intercept code goes here using msg variable alert(msg); // then perform the normal logging tmpConsoleLog(msg); } console.log("Something");
您正在談論的警告是由瀏覽器生成的,而不是console.warn
。 這就是您不能覆蓋它的原因。 很可能,您需要為您需要的每個事件手動添加偵聽器。 例如,如果要處理腳本加載錯誤,請使用onerror
事件:
<script src="https://www.example.com/js/somescript1.js" onerror="console.log('Cannot load script from ' + this.src)"></script> <script src="https://www.example.com/js/somescript2.js" onerror="console.log('Cannot load script from ' + this.src)"></script>
已經很晚了,但這里有一個答案,實際上直接回答了您的問題。
var originalConsoleWarn = console.warn; console.warn = function(message) { doSomethingWithWarn(message); originalConsoleWarn(message); }; function doSomethingWithWarn(message){ console.log("DOING SOMETHING WITH: " + message); } console.warn("hi");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.