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


In reply to WWW::Mechanize::Chrome : how to terminate JS code in eval() and return? (OT JS) by bliako

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.