Define custom function in Firebug - javascript

I am a chronic user of Firebug, and I frequently need to log various stuff so that I can see what I am doing. The console.log function is a lot to type. Even if I assign it to a single letter variable like q = console.log, I have to do it every time I fire up Firebug. Is there any way to do it such that q always refer to console.log (unless, of course, I override it in my session)?

To answer your question, the functionality doesn't currently exist, however I have found the firebug developers to be very responsive in the past. Why don't you put in a feature request on their forum, or better yet, code it up yourself, and ask them to add it?

Depending on your IDE, simply setup a code snippet (I use Flash Develop, so Tools -> Code Snippets).
I believe this to be a better way than setting up redirect scripts and what not, because it stops the Firebug namespace from being polluted, and makes it easier/more consistent to debug if your debugging breaks down.
The screenshot shows me using Flash Develop, hitting Ctrl+B, then hit enter. The pipe (|) in the snippet indicates where the cursor will be placed to start typing after inserting the snippet.

Related

Re-creating a websites javascript function to be used as a stand alone alternative in tampermonkey

I'm looking for a way to do something that may or may not be possible.
On the site http://hitbox.tv/ there is a javascript function I believe that turns text into images.
For example, using:
emotify.emoticons("",{
"emote": ["http://example.com/emote.png", "channel"],
});
in a tampermonkey script or entering it directly into the chrome console would allow all occurrences of "emote" in the chat to be turned into that image.
If I type "emotify" into the chrome console, I'm given:
function (e,f){return f=f||function(h,j,g){return j=(j+", "+g).replace(/"/g,""").replace(/</g,"<"),'<img src="'+h+'" title="'+j+'" alt="" class="smiley"/>'},e.replace(b,function(j,g,m){var k=0,h=m,l=c[m];if(!l){for(;k<d.length&&!d[k].regexp.test(m);)k++;h=d[k].name,l=c[h]}return l?g+f(l[0],l[1],h,m):j})}
and if I type in "emotify.emoticons" I am given:
function (){var k,m,h,o,l=Array.prototype.slice.call(arguments),n="string"==typeof l[0]?l.shift():"",f="boolean"==typeof l[0]?l.shift():!1,g=l[0],j=[];if(g){f&&(c={},d=[]);for(k in g)c[k]=g[k],c[k][0]=n+c[k][0];for(k in c){if(c[k].length>2){for(m=c[k].slice(2).concat(k),h=m.length;h--;)m[h]=m[h].replace(/(\W)/g,"\\$1");o=m.join("|"),d.push({name:k,regexp:new RegExp("^"+o+"$")})}else o=k.replace(/(\W)/g,"\\$1");j.push(o)}b=new RegExp("(^|\\s)("+j.join("|")+")(?=(?:$|\\s))","g")}return c}
So what I'm wondering is, is there a way to use this code in a tampermonkey script somehow so that in the future, if the code is removed from the website, I could still use the emotify.emoticons function to create standalone emotes?
I really hope this makes sense. If you need any more information, fell free to ask. Any help is greatly appreciated!
-Tom
I might be wrong, but my inclination is that no, you can't - because the full behavior for this code is probably actually executed server-side, not in the web browser.
The images would have to get passed to the server to get circulated to the other people in the chatbox anyway
The function you list just returns a function, which does some (somewhat cryptic!) string operations, and little else, indicating the heavy lifting is done elsewhere.
The reason why you can run it using tampermonkey currently is because the function is defined on hitbox.tv. Defining it in tampermonkey probably won't help, because if hitbox removed it, they would also remove everything that uses it, rendering it useless.
You can do more investigation if you feel like it; http://www.hitbox.tv/dist/hitbox-ui.min.js is the link to their (minified) javascript file that runs the website. Running it through http://jsbeautifier.org/ yields a ~55,000 line long file, however, so unless you know what other variable words to search for, it's going to be impractical to comb through by hand.

JS fails unless the console is open

I'm truly stumped by this problem.
I've got some JavaScript to control a product configurator.
A simple bit of code to select some defaults
works fine in Chrome
works fine in IE
doesn't work in Firefox (newest versions of everything)
However, if I do anything to observe the code in FF it works fine.
If I have it alert anything relevant, it works.
If I log anything relevant, it works, but only if the console is actually open so I can see the log. If the console isn't open, doesn't work.
for(type in radio_groups) {
if_checked = !!$(":radio[name="+type+"]:checked").length;
console.log($('.'+type).not('[class*="unavailable"]'));
//This loop doesnt do anything without this log above
alert($('.'+type).not('[class*="unavailable"]'));
// Or this alert.
var t = $('.'+type).not('[class*="unavailable"]');
// Line above doesn't make stuff work.
if(!if_checked)
$('.'+type).not('[class*="unavailable"]').first().click();
}
if_checked is false for every type, I can verify that when it runs.
However, nothing happens.
No buttons are clicked.
This is plain single threaded JS in a browser.
There's no interval/timeout functions on the page.
I can do time arbitrary time consuming tasks before the last line (my best idea was that it was a concurrency issue somehow, I don't see how else logging could affect anything) and it doesn't have any effect.
I can run the same selector and put it in a string, or do anything you can think of to it besides logging or alerting and it wont work; no buttons get clicked. Only actively observing whats happening makes the code work. The entire deal is rather involved and I cant provide the entire thing.
Any ideas on how:
logging can possibly affect the outcome of a simple click event?
why this is Firefox specific? Or other ways I might try to see whats going wrong without the console or alerts?
Edit: Oh, and I've had two other people replicate the issue in their browsers (again, Firefox only), so its not some wonky extension issue unless we all share it.
Thanks.
This line is not valid:
var t = "$('.'+type).not('[class*="unavailable"]')";
It should probably be:
var t = "$('.'+type).not('[class*=\"unavailable\"]')";
or:
var t = $('.'+type).not('[class*="unavailable"]');
Here's a bit of speculation:
if_checked = !!$(":radio[name="+type+"]:checked").length;
It looks like the quotes aren't paired correctly. Did you mean this?
if_checked = !!$(":radio[name='"+type+"']:checked").length;
(See the single quotes that wrap the value of type?)
I've come across this before. If I'm leaving any logging in place in production code I'd wrap it in a try > catch statement.
try {
console.log("my log message")
} catch (err) { };
I know it's considered bad practice to have an empty 'catch' but hey, it's also bad practice to leave the logging in on priduction code.
It seems in FF (also in older IE) if the console is not open then it doesn't exist so the error being caught is probably something like 'console is undefined'

What are the rights ways of debugging javascript?

I made a function called test() in javascript file.Placed a simple alert into it.
In html file, called the method on click of a button. But,it was not being invoked.
Problem was in the 11th function, nowhere related to mine !!!! But, how can a person making his first javascript function suppose to find that out ???
I am looking for best ways to debug javascript.
You can debug javascript using many modern browsers. See this question for details on how to debug in Google Chrome:
How do you launch the JavaScript debugger in Google Chrome?
Furthermore, you shouldn't use alert() for debugging as this can give different results to a production version due to alert() causing a pause in the script.
It is best practice to use console.log() and view the output in the browsers Console.
You can also put debugger in your javascript code to force a breakpoint. However I prefer not to use this as forgetting to remove this before deployment will cause your script to pause, which can be quite embarrassing!
You should use the debug console provided by the browser.
Chrome has it inbuilt, press CTRL + SHIFT + j. In Firefox, install Firebug plugin.
In your code, add alert() to show flow and get values of variables.
Also, use console.log() which will only output to the debug console.
Depending on your browser choice there are debugging options - I tend to use Firefox, so Firebug in my case. There is a question that list options for other browsers - What is console.log and how do I use it?
Unless the project you're working on has already adopted a mechanism for debugging, console.log() tends to be a simple and useful option when tracking down a problem.
Whilst debugging you could take the approach to log out a line when entering a function, like so:
var myFunc = function(el) {
console.log('Inside myFunc');
// Existing code
};
This will enable you to see which functions have been called and give you a rough idea of the order of execution.
You can also use console.log() to show the contents of variables - console.log(el);
Be mindful to remove/disable console.log() calls once you're done as it will likely cause some issues in production.
To answer your question within question,
how can a person making his first javascript function suppose to find that out ???
Well, when something is wrong in JavaScript, for example, you made a syntax error - the script will stop working from there. However, this won't stop HTML from rendering on, so it might look as if everything is correct (especially if your JS is not changing the look of the page) but all the functionality of JS will be dead.
That's why we use the debug tools (listed in the other answers here) to see what's wrong, and in cases like this, it's very easy to notice which function has errors and is causing the whole script to break. This would probably have save a few minutes to your seniors as well.
The best approach would be to test frequently so that whenever you run into errors, you can fix them right away.

Programatically retrieve count of javascript errors on page

I'd like to write a test case (using Selenium, but not the point of this question) to validate that my web application has no script errors\warnings or unhanded exceptions at certain points in time (like after initializing a major library).
This information can easily be seen in the debug consoles of most browsers. Is it possible to execute a javascript statement to get this information programatically?
It's okay if it's different for each browser, I can deal with that.
not so far read about your issue (as far as I understood your problem) here
The idea be the following:
I found, however, that I was often getting JavaScript errors when the page first loaded (because I was working on the JS and was introducing errors), so I was looking for a quick way to add an assert to my test to check whether any JS errors occurred. After some Googling I came to the conclusion that there is nothing built into Selenium to support this, but there are a number of hacks that can be used to accomplish it. I'm going to describe one of them here. Let me state again, for the record, that this is pretty hacky. I'd love to hear from others who may have better solutions.
I simply add a script to my page that will catch any JS errors by intercepting the window.onerror event:
<script type="text/javascript">
window.onerror=function(msg){
$("body").attr("JSError",msg);
}
</script>
This will cause an attribute called JSError with a value corresponding to the JavaScript error message to be added to the body tag of my document if a JavaScript error occurs. Note that I'm using jQuery to do this, so this specific example won't work if jQuery fails to load. Then, in my Selenium test, I just use the command assertElementNotPresent with a target of //body[#JSError]. Now, if any JavaScript errors occur on the page my test will fail and I'll know I have to address them first. If, for some strange reason, I want to check for a particular JavaScript error, I could use the assertElementPresent command with a target of //body[#JSError='the error message'].
Hope this fresh idea helps you :)
try {
//code
} catch(exception) {
//send ajax request: exception.message, exception.stack, etc.
}
More info - MDN Documentation

Getting data from the browser's console using javascript

I don't know if this has been asked before, but what i'd like to be able to do is get data from the error console within the browser itself(if it supports it) this would be for when a user sends off a bug report it'd pull up any errors related to pages at my website for things such as typos in code and other things that somehow managed to slip by. Also, in that regard is there a way to pass the errors from the console to a useable format? If this isn't possible, then i could just tell them to copy and paste what came up from the site itself.
I thought of this right now as i was thinking about how to make the bug reporting system run better since the entire thing is basically ran within the browser and for the backend I can easily just look at error logs but for the frontend ie javascript bits of things it's not goign to be as easy.
So to finish wrap all of this up in one little statement, is there an easy way to get the data from the error console and be able to send it along via javascript ie to a form, or something similar.
You can use the onerror event in JS to get the details of the error. Hoptoad do this for example and log the errors to their console, Their code re-uses lots of nice JS scripts including a printStackTrace function that is great.....
You can see how they do it here:
http://hoptoadapp.com/javascripts/notifier.js

Categories