bliako has asked for the wisdom of the Perl Monks concerning the following question:

use WWW::Mechanize::Chrome; my $mech = WWW::Mechanize::Chrome->new( headless => 1 ); my $console = $mech->add_listener('Runtime.consoleAPICalled', sub { warn join ", ", map { $_->{value} // $_->{description} } @{ $_[0]->{params}->{args} }; }); $mech->get('https://google.com'); # SyntaxError: Illegal return statement at xx line 17. $mech->eval_in_page('if(1){console.log("aaa"); return;} console.log("b +bb");'); # ReferenceError: exit is not defined $mech->eval_in_page('if(1){console.log("aaa"); exit;} console.log("bbb +");'); # Works but is there anything simpler??? $mech->eval_in_page('function xxx(){if(1){console.log("aaa"); return;} + console.log("bbb");} xxx();');

So the question is: how can I have some flow control in eval'ed JS which terminates and returns back to perl? On an error condition say.

The context is: I am trying to get a screenshot of browser's contents using WWW::Mechanize::Chrome. But first I am removing a few HTML elements which obstruct the view, like footers and banners, etc. So, in removing the elements using JS I am sometimes in need to say "element not found" and return back to perl. Of course I can wrap everything in lots and lots of if-then-else but JS has already a lot of curly brackets as it is...

I had the idea of wrapping everything into a single JS function and then return will work just fine. Is there a better, simpler solution?

Many Thanks, bliako

Replies are listed 'Best First'.
Re: WWW::Mechanize::Chrome : how to terminate JS code in eval() and return? (OT JS)
by LanX (Saint) on Apr 12, 2019 at 12:06 UTC
    this is rather in JS question... you should mark the title with (OT JS)

    principally you are looking for "goto" like constructs.

    AFAIK those are in JS

    • function: return
    • loop: break/continue
    • try/catch
    (@all: please feel free to extend if I forgot something)

    IMHO your function solution is the canonical approach, I'd just prefer an anonymous function to avoid potential conflicts with another "xxx".

    (function (){if(1){console.log("aaa"); return;} console.log("bbb");})( +);

    (function(){...})() is analogous to sub {...}->() in Perl.

    If you are worried about the boilerplate, use Perl to wrap the (function(){...})() part around it and extend the class with a new method.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

      Thank you. I will go the function way.