1

I want to know is there any way to click link (open link) on PhantomJS synchronously. First page must be opened first, then click link on the first page to go to second page. Here is my approach using setTimeout:

var page = require('webpage').create();
var url = "http://domain.tld/index.html";

page.open(url, function (status) {
    page.render("1-home.png");

    page.evaluate(function() {
        // search for element and click it to redirect
        document.getElementById("RetailUser").click();
    });

    // I use setTimeout to wait for firstpage to get loaded
    setTimeout(function () {
        // do another process on second page
    }, 5000);

}

PS: I aware I can accomplish it using CasperJS. But if possible, I don't want to use CasperJS.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
justmyfreak
  • 1,260
  • 3
  • 16
  • 30

1 Answers1

3

Clicking a link is always synchronously. What happens afterwards is always asynchronously, because of the asynchronous nature of JavaScript.

There are multiple ways to wait for the next page:

  • Static amount of time with setTimeout,
  • Dynamic waiting for a condition with waitFor,
  • Next page load by registering to page.onLoadFinished before the click,
  • Wait until all outstanding requests are finished (one and two) or
  • A combination of those four methods.
Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • Will read your linkes. By the way, which one do you think will suits my need? The link I click is about 7-10. When setting amount of time with setTimeout there will be time wasted. i.e I set 3s timeout, then page finished loading in 1s. – justmyfreak Nov 23 '15 at 11:20
  • 1
    It really depends on your needs, how the page behaves and how much you are willing to write. I would suggest to start with a simple `page.onLoadFinished` and if that doesn't work move on to `waitFor` to wait for a condition/selector. If this still doesn't work or the condition is too hard to match then try waiting for finished requests and a short `setTimeout` just to be sure. – Artjom B. Nov 23 '15 at 13:34
  • Thanks for your response. I'll try it first. – justmyfreak Nov 24 '15 at 03:03