Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^2: Accessing javascript variable from perl

by frazap (Monk)
on Jun 14, 2019 at 13:42 UTC ( [id://11101351]=note: print w/replies, xml ) Need Help??


in reply to Re: Accessing javascript variable from perl
in thread Accessing javascript variable from perl

The content calls says:
<html><head></head><body><pre style="word-wrap: break-word; white-spac +e: pre-wrap;"> //list of the entries in the headings drop box //the keys give the corresponding elements in the rows var leg = { aa: " ... ", ... }; </pre></body></html>
The return statement gives an error if not included in a 'function () {}'
Error while executing command: executeScript: An unknown server-side e +rror occurred while processing the command.: {"errorMessage":"Return +statements are only valid inside functions",
LanX proposal fails also:
my ($val, $type) = $js->eval_in_page('(function() {return JSON.stringi +fy(leg);})()'); print "val: $val, type: $type\n";
Gives the error
Error while executing command: executeScript: An unknown server-side e +rror occurred while processing the command.: {"errorMessage":"Can't f +ind variable: leg","request":{"headers":{"Accept":"application/json", +"Connection":"TE, close","Content-Length":"74","Content-Type":"applic +ation/json; charset=utf-8","Host":"127.0.0.1:8910","TE":"deflate,gzip +;q=0.3","User-Agent":"libwww-perl/6.15"},"httpVersion":"1.1","method" +:"POST","post":"{\"args\":[],\"script\":\"return (function() {return +JSON.stringify(leg);})()\"}","url":"/execute","urlParsed":{"anchor":" +","query":"","file":"execute","directory":"/","path":"/execute","rela +tive":"/execute","port":"","host":"","password":"","user":"","userInf +o":"","authority":"","protocol":"","source":"/execute","queryKey":{}, +"chunks":["execute"]},"urlOriginal":"/session/95efd1d0-8ea9-11e9-b043 +-85beee600173/execute"}} at C:/strawberry/perl/site/lib/Selenium/Remo +te/Driver.pm line 389.

Update:

The content seems strange to me, should the js code not be include in script tag ?

Replies are listed 'Best First'.
Re^3: Accessing javascript variable from perl
by LanX (Saint) on Jun 14, 2019 at 14:51 UTC
    The errorMessages are explicitly given!

    •  "Return statements are only valid inside functions"

      I explained this already

    •  "Can't find variable: leg"

      so my proposal doesnt fail it's your JS Code. Either you can't access the namespace of leg or you misspelled it.

      Though you may want to try window.leg or play around inside your browser's JS console (normally type F12 to get there)

    HINT: var denotes a lexical var inside a function°, it only becomes global* if used outside.

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

    updates

    °) mostly like my in Perl except for the hoisting effect

    *) in this case it behaves mostly like our in Perl

      With the file jello.jshello.js
      var leg = { aa: "Hello from javascript" } function to_json() { return JSON.stringify(leg); }
      And the file perl.pl
      use strict; use warnings; use WWW::Mechanize::PhantomJS; my $js = WWW::Mechanize::PhantomJS->new(launch_exe=> 'C:/prog/phantomj +s/bin/phantomjs.exe'); $js->get_local("hello.js"); #$js->update_html('<script src="hello.js" type="text/javascript"></scr +ipt>'); #print $js->content; #my ($val, $type) = $js->eval_in_page('JSON.stringify(window.leg);'); my ($val, $type) = $js->eval_in_page('to_json()'); print "val: $val, type: $type\n";
      I can't have any meaningfull result from calling eval_in_page either on the leg var directly or via the function.

      Can you show me how to have this working ?

      Thanks

      Update without phantomjs
      use strict; use warnings; use Log::Log4perl qw(:easy); Log::Log4perl->easy_init($ERROR); use WWW::Mechanize::Chrome; my $js = WWW::Mechanize::Chrome->new(report_js_errors=>1); $js->get_local("hello.js"); #$js->update_html('<script src="hello.js" type="text/javascript"></scr +ipt>'); #print $js->content; #my ($val, $type) = $js->eval_in_page('JSON.stringify(window.leg);'); my ($val, $type) = $js->eval_in_page('to_json()'); print "val: $val, type: $type\n";

      This gives undef for $val whatever I'm calling: the to_json() function or JSON.stringify directly.

        hello != jello

        > I can't have any meaningfull result ...

        Which error message do you get?

        I don't have phantomjs installed, so please provide a reproducible example.

        UPDATE

        I ran your JS code in the browser's console and it works for me:

        > var leg = { aa: "Hello from javascript" } function to_json() { return JSON.stringify(leg); } < undefined > JSON.stringify(leg); < "{\"aa\":\"Hello from javascript\"}" > to_json() < "{\"aa\":\"Hello from javascript\"}"

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

        regarding your update:

        Neither do I have WWW::Mechanize::Chrome installed.

        My suggestions are

        • to make sure your JS is really executed (add an alert to show)
        • and this before you try eval_in_page (you could play around with sleep or a similar wait mechanism)
        HTH!

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11101351]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2024-04-25 08:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found