使PhantomJs在生成pdf之前等待Ajax请求

时间:2018-07-17 19:55:32

标签: phantomjs

使用phantomjs中的示例就像一个魅力

https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js?utm_content=bufferda3e0&utm_source=buffer&utm_medium=twitter&utm_campaign=Buffer

但是,如果URL需要发出Ajax请求以加载其数据怎么办?我可以触发自定义事件,以便仅在随后生成pdf吗?

(我不想猜测请求将花费多少时间并设置超时)

1 个答案:

答案 0 :(得分:1)

此问题的常见解决方案是等待AJAX​​请求完成后将在页面上显示的元素。

包括this example中的waitFor函数,并等待作为参数传递给waitFor的第一个函数返回true,然后它将运行作为第二个参数传递的函数。

page.open("https://example.com/ajaxified/", function (status) {
    waitFor(function() {
        return page.evaluate(function() {
            return document.querySelectorAll(".report").length > 0;
        });
    }, function() {
       page.render("report.pdf");
       phantom.exit();
    });

});