WWW::Mechanize::Chrome How to close a tab

Viewed 340

I can't seem to figure out how to close a tab when using WWW::Mechanize::Chrome.

my $mech = WWW::Mechanize::Chrome->new();
$mech->get('https://www.google.com/');

There is no $mech->close_tab() method.

So the question is, how do you close the tab you're currently working with?

As suggested by @zdim:

my $driver = $mech->driver

Seems to return the Chrome::DevToolsProtocol instance.

Then in order to close the tab, you have to call the close_tab() function and pass the current tab as the argument:

$mech->driver->close_tab($mech->tab);

This approach is generating the following error but it does close the tab:

Calling ->catch in void context at C:/Perl64/site/lib/Chrome/DevToolsProtocol.pm line 567
2 Answers

There is a close_tab method in Chrome::DevToolsProtocol, which is an

asynchronous dispatcher for the DevTools protocol

and does not offer a method to instantiate an object.

The WWW::Mechanize::Chrome has the method driver documented as

Access the Chrome::DevToolsProtocol instance connecting to Chrome.

In a lucky case that this is simple perhaps $chrome->driver->close_tab may do it.

There is also an option driver for its constructor, described as

A premade Chrome::DevToolsProtocol object.

with no further details. Update: using this requires more work.

I cannot yet pursue these clues since the install stubbornly fails at the end, after 54 (fifty-four) distributions are installed.

Hopefully this helps someone to figure it out though.


Update   After forcing the install I can confirm the question update

use warnings;
use strict;
...

my $chrome = WWW::Mechanize::Chrome->new(tab => undef);  # new tab for demo

$chrome->get('https://www.google.com/');

sleep 5;  
$chrome->driver->close_tab($chrome->tab); 
sleep 5;

This does issue a warning

Calling ->catch in void context at .../Chrome/DevToolsProtocol.pm line 567.

which, judged by the code quoted in the message, seems to be exposing a bug.

There is no ->close_tab method because I didn't find a need for it yet.

The "driver" object is a Chrome::DevToolsProtocol object, which is used to talk more directly to Chrome. Blindly calling random methods on random results of methods is recommended here in the comments but is not a method that seems to be fruitful.

If you're hell-bent on closing a tab instead of letting the $mech object go out of scope, you can call

$mech->driver->close_tab( $mech->tab )->get();

but this will break further stuff you might have done with $mech. ->close_tab returns a Future, so you shouldn't discard it blindly.

If you just want no tab to appear, have you considered the headless mode?

This question was cross-posted at https://perlmonks.org/?node_id=1222776 .

Related