Don't Get Wet

Carbonated beverages contain dissolved carbon-dioxide gas. The way to get gas to dissolve in liquid is to pressurize the mixture, meaning that the pressure inside a beer can is greater than the pressure outside the can. This is why you see little bubbles spray out when you open a beer can. Breaking the seal depressurizes the mixture, causing the gas to come out of solution, starthing with the gas closest to the top (that's where the pressure decrease starts). Becasue gas is lighter than liquid, as soon as it comes out of solution, it rises to escape the can. When it escapes, it carries with it a small amount of liquid from the very top of the can because that liquid is blocking its path.

When beer is agitated (shaken), cavities form small bubbles, which then collect as foam on the surface. If you then open the bottle, and explosively decompress the beer, the foam eruption is the work Boyle's law and inflation by diffusion. On the other hand, if the shaken beer is allowed to sit for a while and "decompress," the gass in the bubbles will be driven back into solution by the bubble skin tension making it safe to open.

If you are impatient you can tap on the can. When you tap on the can, you knock bubbles off the bottom and sides of the can, at which point they rise to the top (because gas is lighter than liquid) and there is only a small amount of liquid blocking their escape when you open the can.