in reply to Re^2: fetch HTML page, do javascript, read output from alert/msgbox
in thread fetch HTML page, do javascript, read output from alert/msgbox

In theory, the (Javascript) code that I use in WWW::Mechanize::FireFox::eval_in_page can redefine all functions:

sub eval_in_page { my ($self,$str) = @_; my $eval_in_sandbox = $self->repl->declare(<<'JS'); function (w,str,myalert) { var unsafeWin = w.wrappedJSObject; var safeWin = XPCNativeWrapper(unsafeWin); var sandbox = Components.utils.Sandbox(safeWin); sandbox.window = safeWin; sandbox.window.alert = myalert; // <-- sandbox.alert = myalert; // <-- sandbox.document = sandbox.window.document; sandbox.__proto__ = unsafeWin; var res = Components.utils.evalInSandbox(str, sandbox); return [res,typeof(res)]; }; JS my $window = $self->tab->{linkedBrowser}->{contentWindow}; my $uri = $self->uri; return @{ $eval_in_sandbox->("$uri",$window,sub {print "Alert: @_" +}}; };

Note that the callbacks from MozRepl::RemoteObject are not blocking and not delivered in real time to you, so you can only capture the results of the alert() call but cannot take any action there in Perl. For taking an immediate action, you have to write some Javascript.

I plan a nicer interface for ->eval_in_page that allows you to (re)define properties of the window object, but as currently, WWW::Mechanize::FireFox is under heavy development, I can't promise any timeframe :).

Replies are listed 'Best First'.
Re^4: fetch HTML page, do javascript, read output from alert/msgbox
by TheFlyingCorpse (Novice) on Nov 11, 2009 at 10:55 UTC
    so I can use the code you posted above to pipe the msgBox that is displayed/alert to text instead of having it show as a pop up from the used browser?

    update:
    I edited FireFox.pm version where I replaced the eval_in_page of FireFox.pm with the updated one from you.
    -> The JavaScript uses up to 1 minute to complete, so I get timeout warnings. (command timed out at C:/perl/site/lib/mozrepl/client.pm line 186) (Also edited now to 60 secs)
    -> Found a typo in ur code, you had forgot a ) between }}.
    syntax error at C:/Perl/site/lib/WWW/Mechanize/FireFox.pm line 1294, near "}}"

    This still however does not print to the console, it still gives me the alert up to show.

      I think you still have to pass in and define myalert as a (Perl) subroutine, and you shouldn't edit FireFox.pm but declare your own subroutine for that. I haven't tried capturing alert() myself, as I haven't needed it yet.

        How would I go about and do that?

        I've tried putting your code into my script and making the eval do the javascript:Install() part of it, without success.

        How should I declare a subroutine for myalert?