Hacking Chrome Developer Tools Protocol for fun and profit
I recently came across a tip on Hacker News which along with Firefox, MozRepl plugin and this snippet:
autocmd BufWriteCmd *.html,*.css,*.gtpl :call Refresh_firefox()
function! Refresh_firefox()
if &modified
write
silent !echo 'vimYo = content.window.pageYOffset;
\ vimXo = content.window.pageXOffset;
\ BrowserReload();
\ content.window.scrollTo(vimXo,vimYo);
\ repl.quit();' |
\ nc localhost 4242 2>&1 > /dev/null
endif
endfunction
allows you to refresh a tab in Firefox the moment you save your edits in Vim. No longer do you need to switch to Firefox, hit refresh to see the edits and then come back to your work. This is especially useful when you are on a multi-monitor setup.
My primary browser these days is Google Chrome. I was wondering if such a thing would be possible with Chrome too. It so happens it is. If you start Chrome with –remote-shell-port=9222 switch (on my Mac I do it like this: ~/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome –remote-shell-port=9222), you can connect to it using a TCP socket over port 9222 and then issue it commands using Chrome Dev Tools Protocol.
I wrote a small Perl wrapper around the protocol and then wrote another simple script that simply refreshes the last open tab in your browser:
#refresh.pl
use strict;
use ChromeTool;
my $chrome = ChromeTool->new;
if($chrome) {
my $tabs = $chrome->tabs;
if(scalar(@$tabs) > 0) {
$chrome->eval($tabs->[-1]->[0],
"javascript:window.location.reload()");
}
}
I modified the original Vim snippet mentioned above so that each time I save my code, both the browsers get auto-refreshed:
autocmd BufWriteCmd *.html,*.htm,*.css,*.gtpl,*.tt2 :call Refresh_firefox()
function! Refresh_firefox()
if &modified
write
silent !echo 'vimYo = content.window.pageYOffset;
\ vimXo = content.window.pageXOffset;
\ BrowserReload();
\ content.window.scrollTo(vimXo,vimYo);
\ repl.quit();' |
\ nc localhost 4242 2>&1 > /dev/null
silent !perl -I/Users/deepakg/Projects /Users/deepakg/Projects/refresh.pl
endif
endfunction
Of course, you’ll need to change /Users/deepakg/Projects to where you save the ChromeTool.pm file and refresh.pl. Here is a quick screencast showing this in action:
Credits: I learned about existence of Chrome Developer Tools Protocol from this post. You can also find link to a Ruby REPL client for talking to Chrome on the same page.