4

How to hook into console error and warnings posted by browser. due to internal browser errors. I mean how can I hook into error likes security violation logs

******* ...... it violates the following Content Security Policy directive: "frame-src 'self' *.wholefoodsmarket.com https://*.google.com *.acquia-sites.com".

So I want to get all the error messages present in the console in a single var.

I tried to override the default console functions but not still cannot hook into these types of logs.

My code now

 var consoleLogFn = console.log; var consoleWarnFn = console.warn; var consoleErrorFn = console.error; window.jsErrors = window.jsErrors || []; console.log = function(){ consoleLogFn.apply(console, arguments); var args = Array.prototype.slice.call(arguments); for(var i=0;i<args.length;i++){ pushLog('log', args[i]); } } console.warn = function(){ consoleWarnFn.apply(console, arguments); var args = Array.prototype.slice.call(arguments); for(var i=0;i<args.length;i++){ pushLog('warn', args[i]); } } console.error = function(){ consoleErrorFn.apply(console, arguments); var args = Array.prototype.slice.call(arguments); for(var i=0;i<args.length;i++){ pushLog('error', args[i]); } } console.debug = function(){ consoleErrorFn.apply(console, arguments); var args = Array.prototype.slice.call(arguments); for(var i=0;i<args.length;i++){ pushLog('debug', args[i]); } } var pushLog = function(type, msg){ window.jsErrors.push({ 'type': type, 'message': msg, }); } 
3
  • 1
    You can't, please refer this answer for a possible workaround Commented Oct 27, 2017 at 11:03
  • @ShaharGalukman: I think you dint get my question. I am able to hook into console fns by overriding them . I am also pushing the messages in window.jsErrors array but I cannot hook into error messages that browser throws like security violations. and other stuffs. If you try pasting the above code on your local and try doing console.log('hello'). And then see window.jsErrors you will see you message in the array. Commented Oct 27, 2017 at 11:07
  • 1
    You can use .onerror to listen for js errors if you want, browser errors are not reachable via JavaScript as far as I know.. Commented Oct 27, 2017 at 12:07

1 Answer 1

2

You can listen to errors by adding a lister function.

// You can also do (note the diferent arguments): window.onerror = function (message, source, lineno, colno, error) window.addEventListener("error", function (event) { // do something with the error }) 

For a more detailed description, see: mdn.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.