0

I have an frame based site and i need to click link in the left frame(menu) for getting new content in mainframe. Is this possible to do in phantomjs? Whats the algorythm? Thank you.

var frame = document.getElementsByTagName('frame')[2];
var links = frame.contentDocument.document.getElementsByTagName('a');
for(var l = 0; l < links.length; l++){

     if(links[l].href.indexOf("home") > -1)
     {
       alert(links[l].href);
       //links[l].click();   
     }
}

That stuff doesn't work =\

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user3416803
  • 379
  • 1
  • 2
  • 12
  • What is the issue? You don't know how to click with PhantomJS or you don't know how to find the button that you need to click? – Artjom B. Feb 17 '15 at 13:58
  • Actually, both. No methods that i know to find links on page are working. A piece of javascript code that i posted doesn't work. Thats a fail on the first step. – user3416803 Feb 17 '15 at 14:14

1 Answers1

1

You have to switch to a frame first, before you can do something in it. To actually click an element this question has all the answers:

page.switchToChildFrame(0); // select frame by index or name
page.evaluate(function(){
    function click(el){
        // copied from https://stackoverflow.com/a/15948355
        var ev = document.createEvent("MouseEvent");
        ev.initMouseEvent(
            "click",
            true /* bubble */, true /* cancelable */,
            window, null,
            0, 0, 0, 0, /* coordinates */
            false, false, false, false, /* modifier keys */
            0 /*left*/, null
        );
        el.dispatchEvent(ev);
    }

    click(document.querySelector('a[href*="home"]'));
});
// switch back when you're done
page.switchToParentFrame();

As seen here. You don't need to iterate over the elements to click it. Use querySelector appropriately with an attribute CSS selector. [attribute*=value] selects all elements whose attribute somewhere contains value.

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222