Getting js errors list using javascript [duplicate] - javascript

This question already has answers here:
Get all javascript errors on page/javascript error handling
(4 answers)
Closed 10 years ago.
I want to create a js code snippet which will run onclick of a button on page. After clicking that button it will find whether the console has some errors? (i.e. if its showing some error in status bar in IE) If it has error then it will show an alert box saying that some js code failed on this page. Otherwise will show msg "Passed"
Is it possible to get list of js errors from within the page?

<button id="button">Bug out</button>
<script>
var myErrors = [],
startTrackingErrors = false;
window.onerror = function (errorMessage, url, lineNumber) {
if (!startTrackingErrors) { return false; }
myErrors.push({
errorMessage : errorMessage,
url : url,
lineNumber : lineNumber
});
return true;
};
document.getElementById('button').click = function() {
startTrackingErrors = true;
// put your buggy code here
// loop through "myErrors" array when done
};
</script>

You could use the 'try' and 'catch' directives
try
{
// code that may have an error
}
catch(e)
{
alert('There was an error: '+e.message);
}
finally
{
alert('Execute this bit anyway');
}

As far as I know, it is not possible to read the console output. You can, however, assign a handler to window.onerror to capture all JavaScript errors, that occur inside a page.
Note that this is not implemented in all browsers. I can't find a compatibility table for it right now, though.

Related

this.hasErrors is not a function

I searched for a solution to my problem online but couldn't find any appropriate answer. Although there are tons of this particular question online.
In my typescript file I have the following three methods:
hasErrors() {
// Checking for errors
}
saveItem() {
if (this.hasErrors())
return;
// Save item
}
sendItemToAuthority() {
if (this.hasErrors())
return;
// Send item to authority
}
Somehow this.hasErrors() inside sendItemToAuthority() isn't recognized as a function but in saveItem() it works without any problem. I get the following error in chrome developer tools:
this.hasErrors is not a function
I found following possibility which didn't work for me either (same error message):
sendItemToAuthority() {
var self = this;
if (self.hasErrors)
return;
// Send item to authority
}
Could anyone lead me to a solution? I really don't get why it isn't working.
saveItem() it works without any problem. I get the following error in chrome developer tools this.hasErrors is not a function
You most likely have the wrong this. Use an arrrow function : https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
I finally found a solution. In my constructor I had
this.saveItem = this.saveItem.bind(this);
but forgot to add
this.sendItemToAuthority = this.sendItemToAuthority.bind(this);

How to hide messages in console that came from iframes

I am using console.log(...) for debugging purposes. However the console gets messages from iframes too(I am using iframes in my HTML code). How can I see only the logs that I sent and not the logs that came from iframes?
This is kinda old post, but still, for those who will come here for help:
In Chrome you can check the "Selected context only" (screenshot here) option, and it'll be this.
How about adding a snippet in your JavaScript to catch errors thrown by the iFrames?
You could replace [IFRAME ERROR MESSAGE] with the errors your iFrame is throwing. If the snippet catches an error from an iFrame, it will do nothing, otherwise, it will output the error to the console:
window.onerror = function (msg, url, line) {
if (msg == "[IFRAME ERROR MESSAGE]") {
return true
}
else {
//do nothing
}
}
Make sure to put this code as early as possible in your script.
Reference
Reference 2
Working example (save it as test.html and open in chrome):
<button onclick="myfunction()">x is not defined</button>
<button onclick="myfunction2()">y is not defined</button>
<script>
window.onerror = function (msg, url, line) {
if (msg == "Uncaught ReferenceError: x is not defined") {
return true
}
else {
//do nothing
}
}
function myfunction(){
console.log(x);
}
function myfunction2(){
console.log(y);
}
</script>
In this example, you will see that no errors will be outputted in the console when you click the first button, but you will see errors when you click the second button.
Just filter out (using the Chrome's filter box) the log messages from the iFrame.
In Chrome's Console tab you have a Filter box, type there the name of the file you want to filer out, with a minus sign "-" before the file name.
You can filter multiply files, using space as a delimiter.
For example:
-LogUtil.js -FrameService.js
Or instead of typing, just right click on a log message, and select Hide message from <file_name>.
You can add something like "?nofrm=1" to the src attribute of the page's script tags you want to see logs for. Then in Chrome you can type "nofrm" into the filter to get logs from only them scripts. Add "?nofrm=1" to the url if you want to log inline scripts too.
I wrote a logger service for the client side. I used a pattern by which I can filter out the logs/errors etc which are being produced by my script and not by the iframes.
function logger(){
var pattern="PC:";
var info=function(){
Array.prototype.unshift.apply(arguments, [pattern]);
console.info.apply(console, arguments);
}
var log=function(){
Array.prototype.unshift.apply(arguments, [pattern]);
console.log.apply(console, arguments);
}
var warning=function(){
Array.prototype.unshift.apply(arguments, [pattern]);
console.warn.apply(console, arguments);
}
var debug=function(){
Array.prototype.unshift.apply(arguments, [pattern]);
console.debug.apply(console, arguments);
}
var error=function(){
Array.prototype.unshift.apply(arguments, [pattern]);
console.error.apply(console, arguments);
}
return {
info:info,
log:log,
warning:warning,
debug:debug,
error:error
}
}
Here "PC:" is the pattern
You can filter the logs by source / hide from other scripts than you own. It will of course only be a solution if you get logs from a smaller number of scripts

Error in Custom Google Tag Manager JavaScript

Trying to setup a custom JavaScript in GTM where the innerHTML value is checked for X and if it is X fires.
Here's what I have so far but it's not firing correctly
function() {
var el = document.getElementById('ltrNumPlaceholder');
if (el == null) return 0;
return parseInt(el.innerHTML);
}
I also tried this but GTM complains there there is a syntax error on a line that doesn't exist. (GTM error message for the below is: "Error at line 5, character 2: Parse error. ')' expected.")
function(){
var stepNum = document.getElementById('ltrNumPlaceholder').innerHTML;
if(stepNum == 2)return parseInt(stepNum);
};
Thanks for your help in advance.
To fix the error message, just remove your semicolon at the end of the function (after the closing curly bracket), and that should work.

Getting all table rows and returning them using an XPath query in CasperJS

I'm using Casper.js to automate a regular upload. I've managed to upload the file and check if it's valid, but I'd like to parse the table which is returned if there's errors, but I get the error [error] [remote] findAll(): invalid selector provided "[object Object]":Error: SYNTAX_ERR: DOM Exception 12. Here's the relevant part of my code:
casper.then(function() {
if (this.fetchText('.statusMessageContainer').match(/Sorry, the file did not pass validation. Please review the validation errors in the report below/)) {
this.echo("Upload failed!", "ERROR");
errors = this.evaluate(function() {
var errorRows = __utils__.findAll({
type: 'xpath',
path: '//table[#id="uploadTable"]/tr[position()>1]'
});
return Array.prototype.forEach.call(errorRows, function(e) {
return e;
});
});
this.echo(JSON.stringify(errors));
} else {
this.echo("Upload successful", "INFO");
}
});
Any ideas?
While you probably have an XPath syntax error, you must know that you cannot return DOM elements from a closure passed to the evaluate() method; you have to convert your NodeList and HTMLelement instances to some native Javascript types, eg. Arrays, Objects, strings, etc…
Also, there's a convenient getElementsByXPath() method in the ClientUtils module you can use from the __utils__ instance automatically injected in every page your load:
casper.then(function() {
if (this.fetchText('.statusMessageContainer').match(/Sorry, the file did not pass validation. Please review the validation errors in the report below/)) {
this.echo("Upload failed!", "ERROR");
var errors = this.evaluate(function() {
var errorRows = __utils__.getElementsByXPath('//table[#id="uploadTable"]/tr[position()>1]');
return Array.prototype.map.call(errorRows, function(e) {
return e.innerText; // let's get node text instead of HTMLelement!
});
});
this.echo(JSON.stringify(errors));
} else {
this.echo("Upload successful", "INFO");
}
});
You can also use the ClientUtils bookmarklet to test your selectors right within your browser console as well. For example here, click the bookmarklet and execute this in the js console:
__utils__.getElementsByXPath('//table[#id="uploadTable"]/tr[position()>1]')
Then you'll see if your selector is correct (it works by my side — I mean it is syntactically correct).
Well from your error it appears there is something wrong with your selector.
It's setup correctly from what I can see, except for one thing: Try changing '//table[#id="uploadTable"]/tr[position()>1]' to '//table[#id='uploadTable']/tr[position()>1]' (change "" to '')
Other than that, your XPath looks syntactically correct, so I'm not sure why it would qualify as an invalid selector.

Having IE Issues When Passing Object By Ref. and Dynamically Adding Properties

So, I've created a function to do some error checking on an XML file that I recieve from an AJAX call. Part of the validation is that the function then builds out an object for easy access while I process that data into a form. In FF, works like a charm. IE dies with the error:
Object doesn't support this property or method
Here is the function (minus the un-important bits):
function checkReceiveXMLTagString( doc, messageObject, tag ) {
var tag_nodes = doc.getElementsByTagName( tag );
...do some error checking...
messageObject[tag] = tag_str; <-- error occurs on this line
return true;
}
Here is an example of how the function is call:
if ( checkReceiveXMLTagString( messageObject.Name[0], messageObject.Name[0], "First" ) ) {
...process messageObject.Name[0].First...
}
Like I said, FF has no issues. Safari loads the pages as well. IE has issues.
Thanks!
Looks like something is making messageObject be null or undefined
If the error is on this line:
messageObject[tag] = tag_str;
Then, the only two ways I know of that that can cause an error are:
messageObject is not an object that you can set properties on (null or undefined are the most likely ways that would happen)
tag is null or undefined
Since I see that your code calls this function hundreds of times so you can't effectively just break on it, I'd suggest you put in some defensive coding to check for those conditions and output something to the debug console to identify what the state is when the problem occurs. You can even trigger a conditional breakpoint with code like this:
if (!messageObject || !tag) {
debugger;
}
In the toughest cases, you can put an exception handler around it and break when the exception is thrown:
try {
messageObject[tag] = tag_str;
} catch(e) {
debugger;
}
Both of these will allow you to capture the condition in the debugger and examine all your parameters at the time of the error.

Categories