How to execute javascript code directly in your browser 2007-05-01

This trick is not known by everyone though it is really simple.

The address bar

In the address bar, you simply write

javascript:/*some javascript code here*/;void(0);

As easy as that.

In fact, it's the same thing as creating a link that executes some javascript code.

<a href="javascript:alert('Some code from a link');">Execute code from javascript</a>

The only thing I add is the void(0); at the end of the code to avoid a “bug” that reloads the page.

Hey, if you want to write a bookmarklet, you'll probably use this technique.

Firebug

These days, you can't write javascript without using Firebug (apart if you are a javascript magician). You just can't. For the ones who don't know Firebug, I'll describe it in 7 words : javascript debugger, html inspector, css modifier, fun.

On the “Console” tag, there's one line beginning with “>>>” at the bottom. This is the javascript executer. If you click the red arrow at the end of the line, you have a multi-line executer.

I always use it to write and test the javascript snippets on this site.

What can I do with that?

Everything you want. In fact, I use it for these purpose :
  • write code snippet for Javascript Kata
  • write a bookmarklet
  • debug javascript on Firefox
  • have fun on other's sites


Mastering the date object in javascript 2007-04-27

Javascript has a pretty basic Date object. It is cool but not as cool as in other languages. In fact, it is different but we like it anyway.

The primitive value

A date is nothing else than the number of millisecond since January 1, 1970 00:00:00. So now is 1 177 603 737 358.

When you create a Date object, it is initialized at now. To alert the primitive value (the number of milliseconds since 1970), I simply do.

var now = new Date();
alert(now.valueOf());

Adding and subtracting

Note : You have to know that months in javascript are 0 = january and 11 = december. Just like Java.

This one is easy. When I want to add a number of days (or anything else) to a date, I use the getDate() and setDate() function. When you don't know that the setDate() function (and setHours, setMinutes, setMonths…) has some magic in it, you may have a hard time manipulating the dates.

So, I want to add 3 days to the current date.

var now = new Date();// Add 3 days
now.setDate(now.getDate() + 3);
alert(now);
The problem is when you want to add 3 days to December 31 2006, it should return January 3 2007. No problemo!
var now = new Date();

// Set to December 31 2006 now.setYear(2006); now.setMonth(11); now.setDate(31);

// Add 3 days now.setDate(now.getDate() + 3);

alert(now);

You see that the date is correctly computed. You can do the same things with all the other parts of the date. Magic is in the air!

No formatting

There's no way of formatting a date to a string except if you use concatenation.

If you want to display the YYYY-MM-DD format, you'll have to do this ugly code.

var now = new Date();var nowStr = now.getFullYear().toString() + "-" +
    (now.getMonth()+1 < 10 ? "0" + (now.getMonth()+1).toString() : (now.getMonth()+1).toString()) + "-" +
    (now.getDate() < 10 ? "0" + now.getDate().toString() : now.getDate().toString());

alert(nowStr);

Maybe you won't do it as ugly as this but it won't look pretty. Maybe you should check for a librairy.

The Date.parse() function

Don't use the Date.parse() function. I don't even know which format it takes. It looks like month[sep]day[sep]year but I'm not sure. Better use some regexp and use the setDateUnit function accordingly.

getYear() VS getFullYear()

You should not use the getYear() function. For an obscure reason, it returns the number of years since 1900. You don't want to use it. Trust me.

You are now a master

That's what you need to know about javascript Date object, you are now mastering it.

Do you have something else to add?


Do not use javascript for validations 2007-04-25

This one will be widely accepted. The problem with it is that it's so obvious that the question is asked here and there.

Javascript is not secure

I repeat : javascript is not secure. Your code is readable and it can be modified by anyone. It is great when you want to do a bookmarklet. It is not so great when you want to have a hard as a rock web application.

Example, you want to validate that a manually entered date is less than today. The javascript code for it is not complex.

[source:javascript] function validateDate(theDate) { var now = new Date(); return (theDate < now); } [/source]

But anyone could override the function to always return true and all the dates that he enters would be good. This is bad.

Always validate on the server-side

Whenever you have to validate something in your web application, use the server-side. I know, it is redundant and long to do but you must do it. Someone once said that you must consider every input from the user has evil.I prefer the word dirty. Users sometimes don't want to be evil to a web application but they are. And sometimes, users want to be evil.

If you have little time to implement an application, just do the server-side validations.

You must consider javascript validations as “pretty” validations. It validates things but it just to make your application prettier. In facts, it helps you with usability and it simplifies the life of the users of your application.

The “cheap return” method

To avoid to write a lot of code on the server-side for validations, I would suggest you a simple method that will help you code faster. It is called the cheap return method.

  1. You do all the validations on the client-side in javascript.
  2. You do all the validations on the server-side but if it fails, you display a generic page to the users that says that it has failed.
  3. You pretend to have done it completly on the client-side and server-side.
  4. You spend the rest of your time watching the ceiling.

The idea behind that is that if all javascript validations have passed, the users must have done something between the client-side and server-side. So, he is responsible of that error.

I don't really like it either…


The problem with bookmarklet 2007-04-24

I talked earlier about bookmarklets and how wonderful they are. In today's web2.0 world, you can't have a successful application without giving your users a cool bookmarklet. It can be easy to do sometimes (like the one of del.icio.us) but you always want to do more and it gets more complex… until the day you hit the wall

The problem

You can't execute code without a click of the user. It is obvious to 99,42% of you, but there will be a day when you'll just say “I want to execute some friggin' code without a click from the user”. Even if you want to do it to simplify the life of the user, you can't. There must be a solution.

The solution

For now, the solution is called GreaseMonkey. This is a Firefox add-on that executes javascript automatically when certain pages are called.

Example, I want every background color of every web page I visit to be gray. I would create a script with this code

document.body.style.backgroundColor = "gray";

and it would just work.

The problems of the solution

It is Firefox only. With around 75% market shares, Internet Explorer just can't be forgotten. It is too complex. The user has to know how to install add-ons and how to install greasemonkey scripts. It is way to hard for a normal user.

The real solution

I don't have one and that's why guys that I ask you : how to execute javascript code automatically without a click from the user?

I want all the solutions you can give to me wether it is real or fantasy.

Thanks alot!


How to do a bookmarklet with javascript 2007-04-19

The day I discovered it, I was really happy. Not happy as a fish in water but maybe happy as a cat having its meal (though it enormously depends of which cat we are talking about). Talking about bookmarklet to some of my friends, I saw that there were a lot of incomprehension about it. So I'll begin at the beginning.

What is a bookmarklet?

A bookmarklet is a chunk of javascript code that can be added as a bookmark in your browser. When you click the bookmark, the javascript is executed. This can do a lot of things. To add a bookmarklet, simply drag the link into your bookmark toolbar.

Why does it work?

It works because when a page is loaded in the browser (the client), it has complete power over it. Using javascript, you can do whatever you want without being stopped by some kind of security. Isn't it wonderful?

How to do a bookmarklet

1. Write some javascript that does something useful 2. Put it in a link with the command javascript: before it and void(0); (just to be safe) after it 3. Tell the people to drag the link in their bookmark toolbar

I have to say that the javascript code has to be less than 2083 characters, the limit of characters that enters in the address bar in Internet Explorer.

How to import another JS in a bookmarklet

You want to have a complex “application” executed on a page but you can't do it in less than 2083 characters? As I said earlier, the client has the complete power over the currently displayed page so you can import javascript files in the current page.

var script = document.createElement("script"); script.src="http://www.example.com/javascript.js"; document.body.appendChild(script);

Now, put that on one line add javascript: at the beginning and void(0); at the end and you're set.

Now, let your creativity flow and make a great application.