Javascript debugging in Safari web browser - javascript

I have a JavaScript error in my web project, and this error appears only in Safari 5 web browser. And the problem is Safari says just error message, but not file and line where this error appears. So, I can't find which code cause this error. Does anybody know how can I find code line causes this error?
Here is shot with debugger.
http://xmages.net/storage/10/1/0/d/c/upload/691ce801.png
Thanks for helping.

Click on the "stop sign" icon until it turns blue and then rerun the code. This should make the debugger halt on the line that generated the exception (and allow you to inspect the local variables and execution stack at that point).

thanks for helping!
Problem resolved now. It was jQuery template plugin. It causes this error when some DOM element in template has ID same as template variable name.
E. G.
var template = "<div id="foo">${foo}</div>"
var data = {foo: "bar"}
$.tmpl(template, data)
Solution: Rename ID of template variable name.
var template = "<div id="foo">${bar}</div>"
var data = {bar: "bar"}
$.tmpl(template, data)

Related

How to throw a javascript error during runtime via browser (Chrome)?

My objective: Test out my error handling functionality.
Temporary solution: Have a custom route: /error, which contains code which purposefully produces fatal error.
var a = undefined;
a.b.c // Breaks.
The above works, but I can't use it to test production site as the page is not required.
I was looking for a way to test it via the browser. I tried simply adding"
throw new Error("Custom error thrown here") to the console. That doesn't actually break it during runtime.
I tried adding a break point and adding the same code: throw new Error("Custom error thrown here"). That didn't work either.
Any other easier ways to do this rather than the above?
I was looking for a way where I can do it via browser only.
Thanks.
You did not clearly mention how and where the error should be thrown. I will assume that you can use a modified copy of your JavaScript file to throw errors. The modified file will reside on your computer and only be used when you're using Chrome developer tools. This feature is called Local Overrides. The steps are as follows:
Open the webpage
Open Chrome developer tools for that webpage
In Sources panel go to Overrides tab
Click Select folder for overrides and choose a folder on your computer
A warning appears on the webpage which reads "DevTools requests full access to ..." which you must allow
In Sources panel go to Page tab
Locate the file in which you need to inject the "throw error" code
Right click and choose Save for overrides
Now you can edit the copy of the file on your computer or from within developer tools. Insert the code that produces the error at the desired location. When you reload the page with developer tools open, Chrome will load the local copy of the JavaScript file and throw the error. The error thrown that way will contain the context from where it originated e.g. call stack. If the developer tools are closed then live copy will be used.
If I got your question right, this is How you can do it from the console:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'throw new Error("Custom error thrown here")';
document.body.appendChild(script_tag);
Or if you want you can trigger it on click:
var script_tag = document.createElement('script');
script_tag.type = 'text/javascript';
script_tag.text = 'window.document.onclick = function() { throw new Error("Custom error thrown here")}';
document.body.appendChild(script_tag);
And then you click anywhere on the page, to throw the error;
I would use the exec function which actually takes string and runs the code within at compile time.
exec('a.b.c')
You won't be able to throw an error inside your application from the console, since you are out of scope of the app.
Having said that, one slightly awkward way you could do this is by adding a breakpoint at the start of the javascript file.
Reload the page and your app will pause at the breakpoint - you can then modify the code as you need - like adding a throw new Error("something...") - and save your edits.
Then allow the code to run and you will see your error.
A downside is if you reload the changes will be gone, but I believe it's as close as you can get to modifying code at runtime.
Add this code to your production code
window.addEventListener('err', () => {
throw new Error('break it');
})
and when you want to create an error simply
dispatchEvent(new Event('err'))
in the console
You can use a global variable, which is accessible from your app and from debug console.
if (window.shouldThrow) {
throw new Error("Custom error thrown here");
}
This way you can turn on/off the exception throwing using the window.shouldThrow variable.
Try this way to catch error detail on run time
try
{
var a = undefined;
a.b.c // Breaks.
}
catch ( e )
{
alert("Error: " + e.description );
}

Swift JavaScriptCore not working with large files?

https://github.com/gg2001/monero/blob/master/monero/NewWallet.js
I have a js file that is quite large 6000 lines and JavaScript core does not seem to be able to retrieve variable values whereas running the same file in any web browser works fine for me. When I try to retrieve the value of a variable it shows up as undefined, but when I use a js console in a browswer it shows up fine. I am speculating that this is due to the size of the file because when I put
var helloWorld = "Hello World";
in the front of the js file this swift code can retrieve it
func helloWorld() {
if let variableHelloWorld = self.jsContext.objectForKeyedSubscript("helloWorld") {
print(variableHelloWorld.toString())
}
}
but when I put it at the end it cannot.
Normally this indicates a parsing error. Try adding an error handler to self.jsContext before calling objectForKeyedSubscript() and see if it outputs anything insightful.
self.jsContext.exceptionHandler = { context, exception in
print("JS Error: \(exception?.description ?? "unknown error")")
}
Although your JS code may be valid in a browser console, iOS Safari doesn't support as many Javascript features as newer browsers.
I did see a line in your JS source code beginning with just a semicolon (followed immediately by (function). I wonder if the parser might complain about an empty line without a statement..? Maybe nothing, though.

Javascript "value=..." returns blank page

Follow the following steps.
Steps 1:
Go to google.
Open the javascript console.
Enter the command: document.all.q.value = "hello"
As expected the element with a name of "q" (the search field) is set to "hello").
Steps 2:
Go to google.
In the address bar type javascript: document.all.q.value = "hello!"
Press Enter
If your browser is either Internet Explorer, or Google Chrome, the javascript will have replaced the google website with an entirely blank page, with the exception of the word "Hello".
Finally
Now that you've bugged out your browser, go back to Google.com and repeat Steps 1. You should receive an error message "Uncaught ReferenceError: document is not defined (...) VM83:1
Question:
Am I doing something wrong? And is there another method which works, while still using the address bar for JS input?
The purpose of a javascript: scheme URL is to generate a new page using JavaScript. Modifying the existing page with it is something of a hack.
document.all.q.value = "hello!"; evalues as "hello!", so when you visit that URL, a new HTML document consisting solely of the text hello! is generated and loaded in place of the existing page.
To avoid this: Make sure the JS does not return a string. You can do this by using void.
javascript:void(document.all.q.value = "hello!");
When messing around with javascript: in the adressbar some (if not the most) browsers handle it as a new page, so you have to add a window.history.back(); at the end
javascript: document.all.q.value = "hello!"; window.history.back();

How to catch all javascript warnings and errors to an output div?

i'm using try, catch, for debugging, but warnings is not create exceptions. How to get all javascript warnings and errors to output div?
UPDATED:
If browser supports Afaik logging, how to get that log to string or output div?
UPDATED:
I found the way how to do that:
i can reload console.log function to my custom function an call native console.log function.
First of all, get rid of the try catch. Don't use try catch when you are debugging.
Second, you don't want to out errors to a div, use firebug or inspector for that - console.log();
Third, if you really want to do it: you could use try catch and in the catch, use something like
$('body').append($('div').html('variable for error message goes here'));
if you are using jquery
OR
document.getElementByTagName("body").appendChild( document.createTextNode("variable for error message goes here") );
if you have plain javascript
EDIT: try looking up ie debug bar , ie webDeveloper
I understand myself why someone may want something to actually happen when an error occours in the document. The answers above just say that you would use developer tools, but I needed things to actually happen, and after some searching, here's what I found...
If you wish to catch all errors that come through, you can put the following code into your file, best at the top:
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);
}
I, myself, like to output the errors to a div that contains them all, though you can do literally anything to this information that you could do with any other string passed to a function.
Here is an example of what may happen if you throw an error with a button using the code above:
Error in your.site.here at 1:
Uncaught ReferenceError: foo is not defined
For IE javascript debugging you can follow this guide:
http://msdn.microsoft.com/en-au/library/ie/gg699336(v=vs.85).aspx
Keep in mind that the developer tools window must be open prior to loading the page for the warnings and errors to appear in the console.
For webkit, (chrome, safari) developer console - here is a guide:
https://developers.google.com/chrome-developer-tools/docs/console
...Firefox also has a console

After upgrading to jQuery 1.6.2, globalEval throws an error when trying to execute javascript on page

I upgraded from jQuery 1.4.2 to 1.6.2 and now I get error(in IE). I have JavaScript on the page that gets executed by jQuery globalEval() function
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
In IE the call throws exception:
"Error: Could not complete the operation due to error 80020101."
The data parameter that get executed is javascript variables on page surrounded by <!-- -->
<!--
var id = \"ctrl90900\";
var url = \"myur.com/blah.html\";
-->
I'm using IE9, and jQuery 1.6.2 Not sure why this would cause an error.
If there is any error at all in a script passed to execScript, as far is Internet Explorer is concerned, it will report a 80020101 instead of the original error.
So, also check for missing semicolons and JS features not supported by IE.
For short code passages, i found the most effective debugging technique was to comment out parts of code and see if the error still turns up. If it doesn't, examine the code block that was just commented out for above errors.
It might be the commenting of the code, which is invalid JavaScript and unnecessary in this day and age.
You can strip it out with this regex...
$.globalEval(str.replace(/<!--\s*([\s\S]*?)\s*-->/, '$1'));
jsFiddle.
Just wanted to add a bit to this -- I was getting an error 80020101 whenever in an AJAX-called PHP script that included JavaScript. The script inside the PHP file was also breaking somehow, and refusing to render any of the script in the designated div (other elements of the PHP came through, but nothing inside the JavaScript -- I was trying to draw a chart using HighChart).
Turns out there was an undefined PHP function inside the JavaScript in the included PHP file (used to echo some text). I found this using Firebug.
So bottom line, make sure you don't have any undefined functions inside code coming back via AJAX.

Categories

Resources