I have a program which compiles js from ajax requests with the new Function(), and I am trying to know from which file the error originated, I have tried to
var f = new Function(code);
Object.defineProperty(f, "name", {writable:true});
f.name = 'myFuncName';
But still when an error happens it shows anonymos:2:3
I have also tried to do this
try {
var f = new Function(code);
}catch(e){
console.log(e)
}
But the error doesn't get catched, I think is because the code inside the function is async
Any ideas?
you can try with
var f = function myFuncName (){
return (new Function(code))
.apply(this, arguments)
};
Related
using CEFSharp i try to autoinject a bound Object in the IRenderProcessMessageHandler:OnContextCreated Method but i guess there is a await missing:
_chromeProxy = new ChromeProxy();
chromiumWebBrowser1.RenderProcessMessageHandler = new RenderProcessMessageHandler();
chromiumWebBrowser1.JavascriptObjectRepository.ObjectBoundInJavascript += (mysender, mye) =>
{
var name = mye.ObjectName;
Console.WriteLine($"Object {mye.ObjectName} was bound successfully."); //Gets triggered
};
chromiumWebBrowser1.JavascriptObjectRepository.Register("App", new ChromeProxy(), true);
and the OnContextCreated Method:
public void OnContextCreated(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame)
{
// Does bind but too late ( no await )
const string script = "CefSharp.BindObjectAsync('App');";
frame.ExecuteJavaScriptAsync(script);
// ERR: Uncaught SyntaxError: await is only valid in async function
// const string script = "await CefSharp.BindObjectAsync('App');";
// frame.ExecuteJavaScriptAsync(script);
}
Is it possible to register the bound Object with this approach and if, how could i await the result of the binding before Javascript on the page gets executed?
thanks to #amaitland i got it working:
the key was to use EvaluateScriptAsync instead of ExecuteJavaScriptAsync with the following iife
frame.EvaluateScriptAsync(#"(async function() {await CefSharp.BindObjectAsync('App');})();");
I am new to node.js and I have a simple function which takes to parameters and returns the result of adding those to up:
function DoMath(p1, p2) {
try {
return p1 + p2;
} catch (exception) {
return "sorry, worng output do you want to try again?"
}
}
This function is located it the file app.js.
I also added export of the function: module.exports.DoMath=addTowPharmetrs;
In other file, called app2.js, i am trying to give to parameters to the function and call it:
var key=require("./app.js");
var output=key.addTowPharmetrs(5, 1);
/*expected output: 6*/
console.log(output);
However, the program is not running with the error:
ReferenceError: addTowPharmetrs is not defined
What should I do in order to fix it and make it work?
You mixed up the property name with the local variable name:
module.exports.DoMath=addTowPharmetrs;
should be
module.exports.addTowPharmetrs = DoMath;
I have tried for a couple of days researching on how to create a custom exception in a try/catch.
Here is what I am attempting to do:
I have an included JS file in my html page. The JS file defines a custom object, as well as defining methods for the object.
Next, in the html page I am doing the following:
try {
MyObj = new CustomObj; //from the included JS file.
MyObj.CustomMethod(); //also from the included JS file.
} catch(e) {
alert("Error in either the create of the object, or the method. Error is " + e.description)
}
I need to be able, within the code for the CustomMethod(), to set the Error Object's properties that are captured in the catch statement. For example:
CustomMethod = function{
try{
document.getelementById("field1").value = "my value";
} catch(err) {
//Set the return error
ReturnErr.description = "There was an error!";
}
};
Can this be done? From what I have tried, I have used the throw statement, but it does not effect the Error Object, thus the catch section is never triggered. In face, the custom message is only shown in the Console.
Thanks ahead of time.
Try:
function MyException(_message, _data) {
this.message = _message;
this.data = _data;
this.name = "MyException";
}
Usage
try{
//...
}
catch(_error){
throw new MyException(message, _error);
}
Hope it will help you to sort things out
I would like to put a button in my app, if you press it it will get the contents of everything that was written to the console and email it to me (for reporting bugs). I know I can keep a variable around and every time I do a console.log also append the message to that variable but I am trying to keep the memory consumption of the app low so it would be much more efficient just to grab it from the console.
Is there a way to retrieve the console messages from javascript?
You can't. What's in the console can't be read from JavaScript.
What you can do is hook the console.log function so that you store when it logs :
console.stdlog = console.log.bind(console);
console.logs = [];
console.log = function(){
console.logs.push(Array.from(arguments));
console.stdlog.apply(console, arguments);
}
console.logs contains all what was logged. You can clean it at any time by doing console.logs.length = 0;.
You can still do a standard, non storing, log by calling console.stdlog.
get all console data
how to read browser console error in js?
How to read from Chrome's console in JavaScript
https://www.quora.com/How-do-I-read-console-window-errors-from-Chrome-using-JavaScript
logs
console.defaultLog = console.log.bind(console);
console.logs = [];
console.log = function(){
// default & console.log()
console.defaultLog.apply(console, arguments);
// new & array data
console.logs.push(Array.from(arguments));
}
error
console.defaultError = console.error.bind(console);
console.errors = [];
console.error = function(){
// default & console.error()
console.defaultError.apply(console, arguments);
// new & array data
console.errors.push(Array.from(arguments));
}
warn
console.defaultWarn = console.warn.bind(console);
console.warns = [];
console.warn = function(){
// default & console.warn()
console.defaultWarn.apply(console, arguments);
// new & array data
console.warns.push(Array.from(arguments));
}
debug
console.defaultDebug = console.debug.bind(console);
console.debugs = [];
console.debug = function(){
// default & console.debug()
console.defaultDebug.apply(console, arguments);
// new & array data
console.debugs.push(Array.from(arguments));
}
I have used this code in the past to capture all console activity and store it with types and timestamps in console.everything for sending back to the server for diagnosing form data entry issues. I run this code as early as possible in the <head> element.
if (console.everything === undefined)
{
console.everything = [];
console.defaultLog = console.log.bind(console);
console.log = function(){
console.everything.push({"type":"log", "datetime":Date().toLocaleString(), "value":Array.from(arguments)});
console.defaultLog.apply(console, arguments);
}
console.defaultError = console.error.bind(console);
console.error = function(){
console.everything.push({"type":"error", "datetime":Date().toLocaleString(), "value":Array.from(arguments)});
console.defaultError.apply(console, arguments);
}
console.defaultWarn = console.warn.bind(console);
console.warn = function(){
console.everything.push({"type":"warn", "datetime":Date().toLocaleString(), "value":Array.from(arguments)});
console.defaultWarn.apply(console, arguments);
}
console.defaultDebug = console.debug.bind(console);
console.debug = function(){
console.everything.push({"type":"debug", "datetime":Date().toLocaleString(), "value":Array.from(arguments)});
console.defaultDebug.apply(console, arguments);
}
}
QA Collective's solution is very nice but has a lot of repeated code and doesn't capture errors that are not printed via the console.log, console.error, etc.
Here's the DRY and extended version of his solution that captures more error messages that show up in the console:
if (console.everything === undefined) {
console.everything = [];
function TS(){
return (new Date).toLocaleString("sv", { timeZone: 'UTC' }) + "Z"
}
window.onerror = function (error, url, line) {
console.everything.push({
type: "exception",
timeStamp: TS(),
value: { error, url, line }
})
return false;
}
window.onunhandledrejection = function (e) {
console.everything.push({
type: "promiseRejection",
timeStamp: TS(),
value: e.reason
})
}
function hookLogType(logType) {
const original= console[logType].bind(console)
return function(){
console.everything.push({
type: logType,
timeStamp: TS(),
value: Array.from(arguments)
})
original.apply(console, arguments)
}
}
['log', 'error', 'warn', 'debug'].forEach(logType=>{
console[logType] = hookLogType(logType)
})
}
I also changed the timestamp format to use the ISO format in UTC timezone, to be able to compare time stamps in different time zones more easily.
If you're working on vue.js, you can actually do this:
data () {
return {
data: []
}
},
created () {
let current_log = console.log;
console.log = msg => {
if (msg !== undefined) this.data.push(msg);
current_log.apply(null, arguments);
}
}
All logs from console will be captured and stored in data
If you just want to catch windows errors (Browser's developer tool), you just need to use the window.onerror listener. and the most important thing is to keep returning it false because If you return true in your callback, then the propagation of the error will stop and won't be log in the console anymore .
window.onerror = function myErrorHandler(err, url, line) {
//Do some stuff
console.log(err) // Uncaught SyntaxError: Invalid or unexpected token at Line no:- 1
return false; // so you still log errors into console
}
I'm building a debugging tool for my web app and I need to show console errors in a div. I know I can use my own made console like object and use it, but for future use I need to send all console errors to window. Actually I want to catch console events.
To keep the console working:
if (typeof console != "undefined")
if (typeof console.log != 'undefined')
console.olog = console.log;
else
console.olog = function() {};
console.log = function(message) {
console.olog(message);
$('#debugDiv').append('<p>' + message + '</p>');
};
console.error = console.debug = console.info = console.log
Here's a way using closure, containing the old console log function in the scope of the new one.
console.log = (function (old_function, div_log) {
return function (text) {
old_function(text);
div_log.value += text;
};
} (console.log.bind(console), document.getElementById("error-log")));
None of the answers here consider console messages that get passed multiple parameters. E.g. console.log("Error:", "error details")).
The function that replaces the default log function better regards all function arguments (e.g. by using the arguments object). Here is an example:
console.log = function() {
log.textContent += Array.prototype.slice.call(arguments).join(' ');
}
(The Array.prototype.slice.call(...) simply converts the arguments object to an array, so it can be concatenated easily with join().)
When the original log should be kept working as well:
console.log = (function (old_log, log) {
return function () {
log.textContent += Array.prototype.slice.call(arguments).join(' ');
old_log.apply(console, arguments);
};
} (console.log.bind(console), document.querySelector('#log')));
A complete solution:
var log = document.querySelector('#log');
['log','debug','info','warn','error'].forEach(function (verb) {
console[verb] = (function (method, verb, log) {
return function () {
method.apply(console, arguments);
var msg = document.createElement('div');
msg.classList.add(verb);
msg.textContent = verb + ': ' + Array.prototype.slice.call(arguments).join(' ');
log.appendChild(msg);
};
})(console[verb], verb, log);
});
(An example of a framework that emits messages with multiple parameters is Video.js. But there is certainly many others.)
Edit: Another use of multiple parameters is the formatting capabilities of the console (e.g. console.log("Status code: %d", code).
About errors that are not shown
(Update Dec. 2021)
If any code crashes with an uncaught error, in might not show up in the div. One solution could be, if possible, to wrap all code in a try block to catch such errors and log them manually to the div.
try {
// Code that might throw errors...
} catch(err) {
// Pass the error to the overridden error log handler
console.error(err);
}
Else, if you were concerned at keeping log, warn and error separate from one another, you could do something like this (adapted from MST's answer):
var log = document.querySelector('#log');
['log','warn','error'].forEach(function (verb) {
console[verb] = (function (method, verb, log) {
return function (text) {
method(text);
// handle distinguishing between methods any way you'd like
var msg = document.createElement('code');
msg.classList.add(verb);
msg.textContent = verb + ': ' + text;
log.appendChild(msg);
};
})(console[verb].bind(console), verb, log);
});
where #log is your HTML element. The variable verb is one of 'log', 'warn', or 'error'. You can then use CSS to style the text in a distinguishable way. Note that a lot of this code isn't compatible with old versions of IE.
How about something as simple as:
console.log = function(message) {$('#debugDiv').append('<p>' + message + '</p>');};
console.error = console.debug = console.info = console.log
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="logger" class="web_console"></div>
<script type="text/javascript">
// Overriding console object
var console = {};
// Getting div to insert logs
var logger = document.getElementById("logger");
// Adding log method from our console object
console.log = function(text)
{
var element = document.createElement("div");
var txt = document.createTextNode(text);
element.appendChild(txt);
logger.appendChild(element);
}
// testing
console.log("Hello World...");
console.log("WOW");
/**
console.log prints the message in the page instead browser console, useful to programming and debugging JS using a Android phone
*/
</script>
</body>
</html>
I created a zero-dependency npm module for this case: console-events (surely if you're okay to use nodejs :P)
You can add event listener like that:
const { console } = require('console-events');
console.addEventListener('log', (e) => {
e.preventDefault(); //if you need to prevent normal behaviour e.g. output to devtools console
$('#debugDiv').append('<p>' + message + '</p>');
})