问题
Need a solution for saving log of JavaScript errors. For automated testing any site with support popular web browsers (IE, FF, Chrome).
回答1:
Most practical method is to look for an event onerror. try-catch is the best method, but you should know where in your code is possible to appear an error.
Here alert is used. It can be replaced with an ajax call to some server-side script/app which will be responsible for the database logging of the message. JavaScript by itself can`t access any file-system - server's or user's. This will only send info about the error. demo
window.onerror = function (msg, url, num) {
alert("Error: " + msg + "\nURL: " + url + "\nLine: " + num);
return true;
};
JS-made-poo();
Internet Explorer uses ActiveX, which may be useful in some kind of a logging application. But the user probably will receive a warning when the ActiveX is fired.
回答2:
The simple/best way to do :)
In simple steps:
- Write a JavaScript error trapping code.
- Add Ajax request/response module to send the trapped error to your server.
- at the server store your Javascript errors to a log/database.
- If needed, provide a functionality to access the log remotely.
Logging to a file on client-side has limitations:
- Supported only by IE (using ActiveX Objects)
- Obviously, files are stores on client side. Not at the server.
回答3:
I don't believe there is anything inherent in Javascript to support this as Javascript doesn't get access to the client's filesystem. You'd need to build a browser module, application with an embedded browser, or maybe see if you could build an appropriate firebug extension.
回答4:
Or collect errors in a JS variable and then submit them to a server to log them.
回答5:
Easiest way to do this is to setup a page that you can hit with a post, and on error, post the errors to that page. This requires catching all errors though, so you'd need to wrap your page in a try { .. } catch (e) { .. }
statement.
来源:https://stackoverflow.com/questions/6638132/how-to-save-the-javascript-errors-in-file