Javascript phantomjs 和页面间通信

阅读(2790)

可以认为 phantomjs 中加载的页面是一个隔离的容器,page不能直接调用phantam的变量和方法,需要通过特定方式才能实现和宿主 phantom server 脚本双向通信。

phantom 脚本传递数据到页面 page.evaluate(fn, params)

page.open('http://m.bing.com', function(status) {
    var title = page.evaluate(function(s) {
        return document.querySelector(s).innerText;
    }, 'title');

    console.log(title);
    phantom.exit();
});

注意到,page.evaluate 是个同步方法,第二个参数即为传递进页面的参数。

页面传递数据到 phantom 脚本 window.callPhantom()

page.onCallback = function(data) {
    console.log('CALLBACK: ' + JSON.stringify(data, undefined, 2));
};

page.open('http://m.bing.com', function(status) {
    page.evaluate(function() {
        if (typeof window.callPhantom === 'function') {
            window.callPhantom(document.title);
        }
    });

    console.log(title);
    phantom.exit();
});

window.callPhantom 可以用于一些 jsonp 的场景,将异步请求的 response 回显,解决当前无法直接获取到请求回包 body 内容的问题。

Refer:
http://phantomjs.org/api/webpage/method/evaluate.html
http://phantomjs.org/api/webpage/handler/on-callback.html

Tags: phantomjs