1

I am trying to call a JS function from Phantom JS. The function is actually triggered on clicking a value from select element of the loaded page. This is the closest answer I could get: Call function PhantomJs

Here, the inner HTML is retrieved. But, I just need to call this function and render the page that is loaded after calling this function.

The JS Function is setFilter('2 Days') and the code in the page is <a class="ng-binding" ng-click="setFilter(span)">2 days</a>

My Code:

window.setTimeout(function () {
            page.evaluate(function () {
                setRelativeFilter('Last 2d');
            });
            page.render(output);
            phantom.exit();
        }, waitTime);

Error : ReferenceError: Can't find variable: setFilter

Community
  • 1
  • 1
Hari
  • 57
  • 12

1 Answers1

1

If the function is not defined in global scope then there is probably no way of getting a reference to it to invoke it. You may try to click the link in question.

Here I use document.evaluate to run an XPath expression to find the link based on the text inside.

page.evaluate(function(){
    var xpathResult = document.evaluate(
        "//a[text()='2 days']", 
        document, 
        null, 
        XPathResult.FIRST_ORDERED_NODE_TYPE, 
        null
    );
    if (xpathResult && xpathResult.singleNodeValue) {
        var e = document.createEvent('MouseEvents');
        e.initMouseEvent('click', true, true, window, 
                         0, 0, 0, 0, 0, false, false, 
                         false, false, 0, null);
        xpathResult.singleNodeValue.dispatchEvent(e);
    }
});

I incorporated the clicking from here: PhantomJS; click an element

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • Thank you @Artjom B. The solution by Joe in [link'(http://stackoverflow.com/questions/15739263/phantomjs-click-an-element) worked for me. – Hari Aug 18 '14 at 03:28