带有外部脚本的 PhantomJS 节点

PhantomJS node with external scripts

我用node编写了一个phantomjs脚本来截取网页。我试图截图的页面包含一个重要的外部脚本,它向全局 window 对象添加变量。 IE。 window.__components.

问题是,这从未设置过。它在浏览器中运行良好,但在 phantomJS 中就死了。我已经更改了脚本以在打开页面之前注入脚本,我添加了一个检查以确保在打开页面之前已经添加了组件对象,但它仍然失败。

有什么想法吗?

function injectExternalScripts(page, ph, url) {
    page.includeJs('http://external-script', ()=>{

        page.evaluate(() => {
            return window;
        }, function(result) {
            if(result.__components) {
                openPage(page, ph, url);
            }
        });

    });
}

function openPage(page, ph, url) {
    page.open(url, (status)=>{
        // errors returned from page 
        // window.__components is null
    });
}

您只能 return 来自 PhantomJS 页面上下文的原始对象。 window 和 DOM 节点不是原始对象,如果 __components 也不是原始对象,那么你也不能 return 那。

您可以检查 __components 是否设置为:

page.evaluate(() => {
    return !!window.__components;
}, function(result) {
    if(result) {
        openPage(page, ph, url);
    }
});