AnyEvent-Chromi
view release on metacpan or search on metacpan
lib/AnyEvent/Chromi.pm view on Meta::CPAN
$self->{handle}->on_eof( sub {
$self->{connected} = 0;
if($self->{mode} eq 'client') {
$self->_client_schedule_reconnect();
}
});
$self->{handle}->on_read( sub {
my ($handle) = @_;
my $chunk = $handle->{rbuf};
$handle->{rbuf} = undef;
# Handshake
if (!$ws_handshake->is_done) {
$ws_handshake->parse($chunk);
if ($ws_handshake->is_done) {
if(not $self->{mode} eq 'client') {
$handle->push_write($ws_handshake->to_string);
}
$self->{connected} = 1;
if($self->{on_connect}) {
my $cb = $self->{on_connect};
&$cb($self);
}
}
}
$self->{connected} or return;
# Post-Handshake
$ws_frame->append($chunk);
while (my $message = $ws_frame->next) {
if($message =~ /^Chromi (\d+) (\w+) (.*)$/) {
my ($id, $status, $reply) = ($1, $2, $3);
if($self->{callbacks}{$id}) {
$reply = uri_unescape($reply);
if($reply =~ /^\[(.*)\]$/s) {
&{$self->{callbacks}{$id}}($status, decode_json($1));
}
else {
die "error: $reply\n";
}
delete $self->{callbacks}{$id};
}
}
}
});
if($self->{mode} eq 'client') {
$self->{handle}->push_write($ws_handshake->to_string);
}
}
sub _client_schedule_reconnect
{
my ($self) = @_;
$log->info("connection failed. reconnecting in 1 second");
$self->{conn_w} = AnyEvent->timer (after => 1, cb => sub {
$self->_start_client();
});
}
sub _start_client
{
my ($self) = @_;
$self->{tcp_client} = AnyEvent::Socket::tcp_connect 'localhost', $self->{port}, sub {
my ($fh) = @_;
if(! $fh) {
$self->_client_schedule_reconnect();
return;
}
$self->_setup_connection($fh);
};
}
sub _start_server
{
my ($self) = @_;
$self->{tcp_server} = AnyEvent::Socket::tcp_server undef, $self->{port}, sub {
my ($fh, $host, $port) = @_;
$self->_setup_connection($fh);
};
}
1;
=head1 NAME
AnyEvent::Chromi - Remotely control Google Chrome from Perl
=head2 SYNOPSIS
# Start in client mode (need "chromix-server" or examples/server.pl)
my $chromi AnyEvent::Chromi->new(mode => 'client', on_connect => sub {
my ($chromi) = @_;
...
$chromi->call(...);
});
# Start in server mode
my $chromi AnyEvent::Chromi->new(mode => 'server');
=head2 DESCRIPTION
AnyEvent::Chromi allows you to remotely control Google Chrome from a Perl script.
It requires the Chromi extension L<https://github.com/smblott-github/chromi>, which
exposes all of the Chrome Extensions API via a websocket connection.
=head2 METHODS
=over 4
=item $chromi = AnyEvent::Chromi->new(mode => ..., on_connect => ...);
=over 4
( run in 1.326 second using v1.01-cache-2.11-cpan-39bf76dae61 )