I have a need to find out when a warning (not error) message is sent to the browser's console.log . From research, I know that I can detect error messages with JavaScript code similar to this:
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);
}
But that only shows error messages. It will not show any warning messages.
Is there a similar way to detect a specific warning message in the console.log? Or, alternately, is there some JS code that will allow me to search the console.log for a specific string?
Note that I can see the warning message in the browser's debugging (console logging) window. But I want to 'intercept' the warning message and perform some action if that warning is found.
Added
The intent is to find out when a specific warning message occurs; the message being similar to "Loading failed for the <script> with source "https://www.example.com/js/somescript.js" .
But the question of how to intercept a warning message (not error; the code I included does that) that is output by the browser (not my code).
Added
So, here's what I need. Assume this code
console.warn("Here is a warning!");
What code would you write to see if that message was written to the console as a warning?
The warnings you are talking about are generated by the browser, not console.warn. This is why you cannot override it. Most likely, you need to manually add listeners for each event you need. For example, if you want to handle a script loading error use the onerror event:
<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>
How about overriding the 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");
It's very late, but here's an answer that actually directly answers your question.
var originalConsoleWarn = console.warn;
console.warn = function(message) {
doSomethingWithWarn(message);
originalConsoleWarn(message);
};
function doSomethingWithWarn(message){
console.log("DOING SOMETHING WITH: " + message);
}
console.warn("hi");
Related
I have written a web-crawler to test a pre-release website for errors and issues (i.e. missing content type, timeouts, exceptions, redirects).
This morning a colleague asked me to include a check if there was any javascript error on the page...
A pure javascript solution is unlikely -- i.e. detect all JS errors, using JS
What I appear to want to be able to do is capture the javascript console text, ideally via CoreWebView2
If the page logs each exception into an array,
Errors=[]
window.onerror = function (msg, url, line) {
Errors.push("Caught[via window.onerror]: '" + msg + "' from " + url + ":" + line);
return true;
};
Then you can just query the Errors and see both the count and the nature of the errors.
You can also push errors from try catch
So I have a simple WebAPI Controller with...
[HttpGet]
public string Demo()
{
System.Diagnostics.Debug.Print("API Demo call hit " + DateTime.Now.ToString());
return "Got Here";
}
Because of the Debug output, I can tell that it is actually getting called from my javascript. So I know that my script is at least connecting. I also know that if I put a break on the line.. the script (html page) does pause and wait until I let the code continue. So they are talking, but I have 2 issues...
1) Every time I make a send call, I get the script error "NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost:64769/api/demo'" ... even though I know it is talking to it. But I did notice that if I do NOT trap for errors, the script fails on the "Send" line and doesn't continue.
2) However, with the error trap, the script does continue (as expected) but the XMLHttpRequest doesn't have my return. (e.g. responseText is blank).. pretty much every single property of the object is blank or null.
So I think my response is empty because there is a problem with the "send". However because it is actually calling my Controller and waiting on it to run, I'm lost as to what the problem is?
Here is my script...
function CallWebAPI()
{
var displayResults = document.getElementById('responseDetails');
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost:64769/api/demo", false);
try
{
xmlhttp.send();
}
catch(err)
{
displayResults.innerHTML += err + "<br />";
}
displayResults.innerHTML += "The Results...<br />";
for (var key in xmlhttp)
{
displayResults.innerHTML += key + "---" + xmlhttp[key] + "<br />";
}
}
All,
So after an entire day and half of messing around, finally figured it out. I guess I was running an HTML file from my desktop, and my Web Service was running on http://localhost:64769.
This is one of those cross domain things. When using an HTTP client in .NET, I did not have to deal with this.. but once I tried to use a client other than .NET, my Web service actually responded.. but the client Browser would not accept the response.
The fix was to change my api service to...
[HttpGet]
public HttpResponseMessage Demo()
{
string myReturnMessage = "API Demo call hit " + DateTime.Now.ToString();
System.Diagnostics.Debug.Print(myReturnMessage);
HttpResponseMessage myReturn = this.Request.CreateResponse(System.Net.HttpStatusCode.OK, myReturnMessage);
//This was the KEY!!!!
myReturn.Headers.Add("Access-Control-Allow-Origin", "*");
return myReturn;
}
I want to implement the global error handling for Ajax calls in my angular Js Application . I think $httpprovider works for $http requests only. Kindly guide me in achieving this. How can i write the interceptor for capturing the failure of Ajax calls. My main goal is to capture the failure of Ajax call into google Analytics.
Write ajax call inside javascripts try-catch
http://www.w3schools.com/js/js_errors.asp
You can try to listen to window.onerror event but it will catch all js errors, so you need to filter them.
window.onerror = function(msg, url, line, col, error) {
// Note that col & error are new to the HTML 5 spec and may not be
// supported in every browser. It worked for me in Chrome.
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;
// You can view the information in an alert to see things working like this:
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
// TODO: Report this error via ajax so you can keep track
// of what pages have JS issues
var suppressErrorAlert = true;
// If you return true, then error alerts (like in older versions of
// Internet Explorer) will be suppressed.
return suppressErrorAlert;
};
You can read more about it in this question.
Just a simple .js file in one of my drive which contains code
var x=3;
function numSqaure(x)
{
return(x*x);
}
var sentence="The square of" + x + "is" + numSqaure(x);
console.log(sentence);
I'm trying to run it through Powershell but it shows an error 'console' is undefined .
How to handle this error? I want it through Powershell only.
Javascript files are made for being executed by a browser, not directly in console unless you're using Node.js or something similar.
Create an HTML with a script tag like this:
<script src="c:\whatever\folder\you\choose\yourscript.js"></script>
and enter developer tools in browser. There this error won't happen anymore and console will exist.
How can I close endless alert in PhantomJS?
a website has endless alert
I used
page.onAlert = function(msg) {
console.log('ALERT: ' + msg);
};
to check whether the website has alert
but this method you will never stop because that's an endless alert
You don't have to print all alerts that the page you're visiting sends your way. Simply remove the handler to silence them:
page.onAlert = function(msg) {
console.log('ALERT: ' + msg);
page.onAlert = function(){};
};
This prints only the first alert. You can make this more sophisticated by adding counting alerts or something like that.
Try this for every reloaded page that would have an alert later.
driver.execute_script("window.confirm = function(){return true;}");
See more reference here.