This may be dumb question. But somehow this engaged me for sometime and after some basic research I couldn't find an answer.
I was learning JavaScript and a code I wrote had an error and has been outputting infinite loops of alerts. I tried the normal shortcuts like Ctrl + C and Ctrl + Z but they didn't work. So I was thinking if there is any solution to this other than ending the browser process (like by doing a Ctrl + Alt + Del).
There are workarounds, as #Sarfras mentions, but no magic button that'll save you. The F5 workaround is the best I know of.
If you are using firebug, I would suggest you look into using the log feature rather then alerts. Many people find this as a useful way of debugging.
http://getfirebug.com/logging
If you are using alert as a debugging method, I strongly suggest you use the firebug plugin.
With it, you can use console.debug("whatever message", whatever, values).
Otherwise, if your intent is to actually use a dialog message, you could use some of these dialogs rather than the browser's built-in dialogs. Besides being a standard way of showing messages, they are way nicer ;)
You can log errors without a specific browser, with a global array.
This method allows you to 'turn off' an infinite alert,
but still be able to read the error log.
var logErrors= true, errorLog= [];
function Yikes(str){
if(str.constructor==Error)str=str.message;
errorLog.push(str);
if(logErrors== true){
logErrors= confirm(str+'\n keep showing errors? ');
}
return true;
}
window.onerror=Yikes;
you can also use it around problem code,
to return values:
try{
d2= Date.fromUTCArray(D.slice(0, D.length));
}
catch(er){
return Yikes(er.message+', '+D);
}
Related
I am trying to detect when an HBO Go movie has completed using javascript. Unfortunately, HBO Go uses Flash, and I have no Flash experience.
I noticed that when the movie ends, the Chrome javascript console shows this:
00:02:30:0596 TimeEvent.COMPLETE
(anonymous function) # VM12786:1
I followed VM12786:1 and found this:
try { __flash__toXML(console.error("00:02:30:0596 TimeEvent.COMPLETE")) ; } catch (e) { "<exception>" + e + "</exception>"; }
I'm not quite sure what either of these mean. Can someone briefly explain it? I have extensively googled, but haven't found anything that I understand.
And, is there any way that I can detect with javascript or jQuery that this has been triggered?
Here's a briefing on those JS bits:
try {
__flash__toXML(console.error("00:02:30:0596 TimeEvent.COMPLETE"));
} catch (e) {
"<exception>" + e + "</exception>";
}
The __flash__toXML function is a mechanism to allow the Flash program to communicate with the webpage via JavaScript (brief explanation here, unrelated article). It seems like that snippet is part of a larger section that handles the video ending event.
The weird stringy thing seems like a useless piece of code that is just there as a placeholder, but I would need to look at the context to understand it better. As it is, it does nothing.
Here's my answer to your question:
Unfortunately, there's no event you can capture for console actions directly. You would need to replace the functions with your own that trigger a custom event, and then handle that event. This article explains the process excellently. You would need to modify the internal intercept function to trigger an event on the main window, which you can handle in the traditional ways:
$(window).trigger("myapp.console.log");
Note: This may not work for content scripts, but that's advanced and depends on implementation. If you are using something injected into the browser, replacing the function will only affect the content script's sandbox.
I learned on StackOverflow that you can hijack the console functions, as in the example, where I've added an alert to the console.error function.
var conerr = console.error;
console.error = function()
{
alert("console error: " + arguments[0]); /* do stuff here */
return conerr.apply(console, arguments);
}
setTimeout(function() {console.error("00:02:30:0596 TimeEvent.COMPLETE");}, 1000);
I have a 17000 line page with lots of HTML/JavaScript/jQuery and it's always frustrating when I make a typo and there's no clue when the page loads into the browser what the problem is. It just - doesn't do anything. Consider the patch of code below, for example, where the third line terminates with a ' instead of a ; .
$(document).on('click', 'input#answer_chkbx', function(e) {
if(e.target.checked){
x$ = g.currentElement$.find('.cellContent')'
g.currentElement$.addClass('answerBox')
.css('background-color','tansparent')
.height(25)
.width(150);
}
});
There should be something that runs through the code and finds that immediately.
Is there a way to check for things like this?
Thanks
You might consider a tool such as JSLint or JSHint.
For offline coding you can use Netbeans IDE or Dreamweaver
I'd like to receive callbacks from Javascript code to my Silverlight host without using ScriptableAttribute. I've seen it done before, but I couldn't work out how they did it. Has anyone got any ideas? Thanks
Simple enough use:-
HtmlPage.Window.Invoke("someJavascriptFunc", "Hello", "World");
In the javascript in the page hosting the silverlight have:-
function someJavascriptFunc(p1, p2)
{
alert(p1 + ' ' + p2);
}
Edit: Ken is right the above is the wrong way round.
Lets say you have this function in Silverlight:-
string GetStuff(string name)
{
return "Hello " + name;
}
You can now make this function available to javascript like this:-
HtmlPage.Window.SetProperty("sayHello", new Func<string, string>(GetStuff));
Now code in javascript can simply do something like this:-
alert(sayHello("Fred"));
If you're using events, in theory, you can use AttachEvent to subscribe to events. That's not quite the same thing as callbacks, but it's close.
Caveats: I haven't tested AttachEvent on Mozilla-based browsers (where the appropriate JS command is "addEventListener()" rather than "attachEvent()"), and I've had trouble getting AttachEvent() to work reliably even in IE. So I've always just used the [ScriptableMember] attribute, and called that from JS. Is there a reason you don't want to use that? (I'd be curious to hear if anyone has any better ideas.)
Is it possible to add messages to the built-in error console of Firefox from JavaScript code running in web pages?
I know that I there's Firebug, which provides a console object and its own error console, but I was looking for a quick fix earlier on and couldn't find anything.
I guess it might not be possible at all, to prevent malicious web pages from spamming the log?
If you define a global function that checks for the existence of window.console, you can use Firebug for tracing and still plays nice with other browsers and/or if you turn Firebug's console tracing off:
debug = function (log_txt) {
if (typeof window.console != 'undefined') {
console.log(log_txt);
}
}
debug("foo!");
You cannot write to the console directly from untrusted JavaScript (e.g. scripts coming from a page). However, even if installing Firebug does not appeal to you, I'd recommend checking out Firebug Lite, which requires no installation into the browser (nor, in fact, does it even require Firefox). It's a script which you can include into any web page (even dynamically), which will give you some basic Firebug functionality (such as console.log()).
Yes, you can =P
function log(param){
setTimeout(function(){
throw new Error("Debug: " + param)
},0)
}
//Simple Test:
alert(1)
log('This is my message to the error log -_-')
alert(2)
log('I can do this forever, does not break')
alert(3)
Update to a real function
This is a simple hack, just for fun.
window.console is undefined in Firefox 4 beta 6 even if Firebug 1.6X.0b1 is enabled and open, probably because of privilege issues that others discuss. However, Firefox 4 has a new Tools > Web Console, and if this is open you have a window.console object and untrusted JavaScript code on the page can use console.log(). The Web Console is in flux (see https://wiki.mozilla.org/Firefox/Projects/Console), you may need to change settings named devtools.* in about:config , YMMV.
I would just install Firebug and use console.log. If you can't do that, though, you can always throw an error:
throw "foobar";
throw new Error("bazquux");
Of course, this will break you out of the code that you're currently executing, so you can't use it for detailed logging, but if you can work around that I think it's the only way to get something logged out of the box.
AFAIK, it is not possible. But if you are interested in how extensions in Firefox interact with the error console, check this out.
This function does not require any extension nor library. However it grants full privileges to the relevant website. No worries since you are the one developing it, right?
// Define mylog() function to log to Firefox' error console if such a
// thing exists
function defineMyLog()
{
// Provide a useless but harmless fallback
mylog = function(msg) { };
// return; // disable in production
if (typeof(netscape) === "undefined") {
// alert("Logging implemented only for Firefox");
return;
}
// The initial auth popup can be avoided by pre-setting some magic user_pref
// ( "capability.principal.codebase.p0.granted", "UniversalXPConnect"), etc.
try {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
} catch (e) { // User has denied privileges
// alert(e.name + ": " + e.message);
return;
}
ffconsoleService = Components.classes["#mozilla.org/consoleservice;1"]
.getService(Components.interfaces.nsIConsoleService);
mylog = function (msg)
{
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
ffconsoleService.logStringMessage(new Date().toLocaleTimeString() + ": " + msg);
}
mylog("Firefox logging function has been defined");
// window.open("javascript:"); // this URL does not work anymore?
}
If you're interested, check out a script I wrote -- it's a "cheap" Firebug replacement that doesn't interfere with any normal console (like Safari or Chrome) but does extend it with almost all the Firebug methods:
http://code.google.com/p/glentilities/
Look under the hood and you'll see what I mean by "cheap". :-)
Combine it with YUI or json.org's JSON serializers to sorta replicate console.dir.
Firebug and Firebug Lite are definitely nicer GUIs, but I use my home-grown one all the time to retain logging safely even for production code -- without constant commenting & un-commenting,
I realise this is not the ideal place to ask about this in terms of searchability, but I've got a page whose JavaScript code throws "Stack overflow in line 0" errors when I look at it in Internet Explorer.
The problem is quite clearly not in line 0, but somewhere in the list of stuff that I'm writing to the document. Everything works fine in Firefox, so I don't have the delights of Firebug and friends to assist in troubleshooting.
Are there any standard causes for this? I'm guessing this is probably an Internet Explorer 7 bug or something quite obscure, and my Google-fu is bringing me little joy currently. I can find lots of people who have run into this before, but I can't seem to find how they solved it.
I ran into this problem recently and wrote up a post about the particular case in our code that was causing this problem.
http://cappuccino.org/discuss/2010/03/01/internet-explorer-global-variables-and-stack-overflows/
The quick summary is: recursion that passes through the host global object is limited to a stack depth of 13. In other words, if the reference your function call is using (not necessarily the function itself) was defined with some form window.foo = function, then recursing through foo is limited to a depth of 13.
Aha!
I had an OnError() event in some code that was setting the image source to a default image path if it wasn't found. Of course, if the default image path wasn't found it would trigger the error handler...
For people who have a similar problem but not the same, I guess the cause of this is most likely to be either an unterminated loop, an event handler that triggers itself or something similar that throws the JavaScript engine into a spin.
You can turn off the "Disable Script Debugging" option inside of Internet Explorer and start debugging with Visual Studio if you happen to have that around.
I've found that it is one of few ways to diagnose some of those IE specific issues.
I had this problem, and I solved it. There was an attribute in the <%# Page tag named MaintainScrollPositionOnPostback and after removing it, the error disapeared.
I added it before to prevent scrolling after each postback.
If you came here because you had the problem inside your selenium tests:
IE doesn't like By.id("xyz"). Use By.name, xpath, or whatever instead.
Also having smartNavigation="true" causes this"
I set up a default project and found out the following:
The problem is the combination of smartNavigation and maintainScrollPositionOnPostBack. The error only occurs when both are set to true.
In my case, the error was produced by:
<pages smartNavigation="true" maintainScrollPositionOnPostBack="true" />
Any other combination works fine.
Can anybody confirm this?
Internet Options
Tools
Internet options
Advanced
Navigation section
Click > Disable script debugging
display a notification about every script error
sign in
You will smile !
My was "at line 1" instead but...
I got this problem when using jQuery's .clone method. I replaced these by using making jQuery objects from the html string: $($(selector).html()).
I have reproduced the same error on IE8. One of the text boxes has some event handlers to replace not valid data.
$('.numbersonly').on("keyup input propertychange", function () {
//code
});
The error message was shown on entering data to this text box. We removed event "propertychange" from the code above and now it works correctly.
P.S. maybe it will help somebody
I don't know what to tell you, but the same problem occured with jQuery table sorting and SEARCH.
When there is nothing left in the table, where you are searching a string for example, you get this error too. Even in Google Analytics this error occurs often.
In my case I had two functions a() and b(). First was calling second and second was calling first one:
var i = 0;
function a() { b(); }
function b() {
i++;
if (i < 30) {
a();
}
}
a();
I resolved this using setTimeout:
var i = 0;
function a() { b(); }
function b() {
i++;
if (i < 30) {
setTimeout( function() {
a();
}, 0);
}
}
a();
This is problem with Java and Flash Player. Install the latest Java and Flash Player, and the problem will be resolved. If not, then install Mozilla Firefox, it will auto install the updates required.