Last active
June 30, 2018 17:38
-
-
Save jbarber/6451157 to your computer and use it in GitHub Desktop.
Reload Chrome tabs from the command line with Perl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
=head1 NAME | |
chrome-reload | |
=head1 SYNOPSIS | |
chrome-reload 1 | |
=head1 DESCRIPTION | |
Reload tabs in the chrome browser. | |
Requires that the browser has been started with remote debugging enabled: | |
google-chrome --remote-debugging-port=9222 --user-data-dir=remote-profile | |
Tabs are indexed from 1 - the 0'th tab (default) is the currently active tab. | |
=head1 SEE ALSO | |
Chrome Remote Debugging Protocol - L<https://developers.google.com/chrome-developer-tools/docs/protocol/1.0/index> | |
=head1 AUTHOR | |
Jonathan Barber - jonathan.barber@gmail.com | |
=head1 COPYRIGHT | |
Copyright (C) 2013, Jonathan Barber | |
This program is free software, you can redistribute it and/or modify it under the same terms as Perl 5.10. | |
=cut | |
use strict; | |
use warnings; | |
use 5.10.0; | |
use JSON::Any; | |
use LWP::Simple; | |
use IO::Async::Loop; | |
use Protocol::WebSocket::URL; | |
use Net::Async::WebSocket::Client; | |
my $j = JSON::Any->new; | |
sub get_browser_tabs ($) { | |
my ($url) = @_; | |
my $tabs = get $url; | |
return $j->decode($tabs); | |
} | |
sub get_tab_url ($$) { | |
my ($url, $tab) = @_; | |
my @tabs = @{ get_browser_tabs($url) }; | |
$tab < @tabs || die "No tab $tab\n"; | |
return $tabs[$tab]->{webSocketDebuggerUrl}; | |
} | |
sub ws_url_decode ($) { | |
my $u = Protocol::WebSocket::URL->new->parse(shift); | |
return (host => $u->host, service => $u->port); | |
} | |
# JSON to reload a tab | |
sub reload () { | |
$j->encode({ | |
id => 1, | |
method => "Page.reload", | |
params => { | |
#url => 'http://www.fe.up.pt#foo', | |
}, | |
} | |
); | |
} | |
my ($host, $port, $tab) = qw(localhost 9222 0); | |
$ARGV[0] && ($tab = $ARGV[0]); | |
my $ws_url = get_tab_url("http://$host:$port/json", $tab); | |
my $loop = IO::Async::Loop->new; | |
my $client = Net::Async::WebSocket::Client->new( | |
on_frame => sub { | |
my ( $self, $frame ) = @_; | |
$loop->stop; | |
}, | |
); | |
$loop->add( $client ); | |
$client->connect( | |
ws_url_decode $ws_url, | |
url => $ws_url, | |
on_connected => sub { | |
$client->send_frame( | |
masked => 1, | |
buffer => reload(), | |
); | |
}, | |
on_connect_error => sub { die "Cannot connect - $_[-1]" }, | |
on_resolve_error => sub { die "Cannot resolve - $_[-1]" }, | |
); | |
$loop->loop_forever; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment