These days, when the phrase "headless browser" is mentioned, you immediately think of PhantomJS, but - there are alternatives. In this article, I am going to introduce a nice alternative you can use on Linux which allows you to run real browsers - Firefox and Chrome, headless - using Xvfb.
What's Wrong With PhantomJS?
Run Real Browsers Headless
Xvfb is a virtual display framebuffer for X - the display system used by Linux. It provides a fake display buffer for graphical programs to write to, thus allowing any program to run headlessly.
If you are running Debian or Ubuntu and are using apt-get, installing is simply as:
apt-get install xvfb
If you are on CentOS and using yum, it's
yum install xorg-X11-server-Xvfb
Installing the Browsers
On Ubuntu, I found installing Chrome and Firefox painless.
- For Chrome simply go to the Chrome download page, download the .deb file, then do
dpkg -i <the path to the .deb file>to install.
- For Firefox, it's just
apt-get install firefox.
On CentOS, I have had more trouble.
- For starters, Chrome is not supported on CentOS and I haven't even found a simply way to build Chrominum and I gave up.
- Installing firefox also had a little hiccup: I ran
yum install firefox, but then running
firefoxresulted in an error, which I solved by also installing
yum install gdk-pixbuf2.
The usage of Xvfb is:
xvfb-run <some command>
That's all you need to know! For example, you can run Firefox within Xvfb:
xvfb-run firefox http://google.com
This should just start a firefox process in the background. You may see a cryptic warning in the terminal, but otherwise it's not very exciting because you don't actually see anything.
If you use Testem to run tests, you can do:
xvfb-run testem -l firefox
to run your tests in Firefox or
xvfb-run testem -l chrome
to run them in Chrome - headless!
Of course, this is not limited to Testem, you can use
xvfb-run with Karma, Grunt, Gulp or any other test runner that spawns a real browser and it will just work.
If you use Linux for development, this is an attractive solution. It allows you to run your tests without having an unwanted window and it's easy to setup and use. However, even if you don't use Linux for development, you may still use Linux for continuous integration, in which case, maybe you are currently using PhantomJS to run tests. If that's working well for you, great. But if PhantomJS is starting to create unwanted overhead for you, consider switching to this setup.