perlmechanizewww-mechanize-firefox

going to a javascript link with mechanize-firefox


There is a link on a page, and I want to go to it but it just a javascript command. How with mechanize do I go to the link?

<a href="javascript:__doPostBack(&#21;ctl54$cphMainContent$resultsGrid$ctl54$ctl25$ctl62$ctl13&#24;,&#56;&#56;)"><span>abc</span></a>

Solution

  • Without the page and its HTML and JS one can only guess. Note that the follow_link() methods don't work with JS links. The method below does, but of course I cannot test without the page.

    Probably the best bet is to get link(s) as DOM object(s) for the click method

    use WWW::Mechanize::Firefox;
    # Get to your page with the link(s)
    my $link = find_link_dom( text_regex => 'abc' );   # Or use find_all_links_dom()
    $link->click();  
    # $mech->click( { dom => $link } )  # works as well
    

    There are also text and text_contains relevant options (instead of text_regex), along with a number of others. Note that click method will wait, on a list of events, before returning. See for example this recent post. This is critical for pages that take longer to complete.

    See docs for find_link_dom() and click methods. They aren't very detailed or rich in examples but do provide enough to play with and figure it out.

    If you need to interrogate links use find_all_links_dom(), which returns an array or a reference to array (depending on context) of Firefox's DOM as MozRepl::RemoteObject instances.

    my @links_dom = find_all_links_dom( text_contains => 'abc' );
    
    # Example from docs for find_link_dom()
    for my $ln (@links_dom) {
        print $ln->{innerHTML} . "\n"
    }
    

    See the page for MozRepl::RemoteObject to see what you can do with it. If you only need to find out which link to click the options for find_link_dom() should be sifficient.


    This has been tested only with a toy page, that uses __doPostBack link, with <span> in the link.