【问题标题】:How to return window.performance object to CasperJS scope如何将 window.performance 对象返回到 CasperJS 范围
【发布时间】:2015-07-01 14:59:59
【问题描述】:

我正在尝试使用以下代码将 web 页面中的 window.performance 对象返回到 casper 的范围,但我得到了 null。谁能解释一下原因?

    performance = casper.evaluate ->
        return window.performance
    @echo performance

【问题讨论】:

    标签: coffeescript phantomjs casperjs


    【解决方案1】:

    PhantomJS 1.x 没有实现window.performance,所以你不能使用它。

    PhantomJS 2.0.0 实现了它,但没有实现 window.performance.toJSON() 函数。 PhantomJS 的问题是你必须通过evaluate() 访问这些信息,但它有以下限制:

    注意:evaluate 函数的参数和返回值必须是简单的原始对象。经验法则:如果可以通过 JSON 序列化就可以了。

    闭包、函数、DOM 节点等将起作用!

    您必须找到自己的方式在页面上下文中序列化 this 并将其传递到外部 (JavaScript):

    var performance = casper.evaluate(function(){
        var t = window.performance.timing;
        var n = window.performance.navigation;
        return {
            timing: {
                connectStart: t.connectStart,
                connectEnd: t.connectEnd,
                ...
            },
            navigation: {
                type: n.type,
                redirectCount: n.redirectCount
            },
            ...
        };
    });
    

    或寻找产生可序列化对象的深拷贝算法 (from here):

    var perf = casper.evaluate(function(){
        function cloneObject(obj) {
            var clone = {};
            for(var i in obj) {
                if(typeof(obj[i])=="object" && obj[i] != null)
                    clone[i] = cloneObject(obj[i]);
                else
                    clone[i] = obj[i];
            }
            return clone;
        }
        return cloneObject(window.performance);
    });
    console.log(JSON.stringify(perf, undefined, 4));
    

    【讨论】:

    • 谢谢,但你的意思是我不能将它用于 PhantomJS 1.9.x?如果我可以在页面上下文中对其进行序列化并返回 JSON 对象,那么幻影的版本是什么无关紧要?就像我可以很好地检索 window.performance.timing.value
    • PhantomJS 1.x 根本没有window.performance,所以没有什么要序列化的。
    • 但是如果代码不是在幻影所在的页面上执行的所有内容?如果你说的是真的,我应该无法从 window.performance.timing 中检索任何值,对吧?
    • 是的。使用 PhantomJS 1.9.x 时,您是否能够从 window.performance.timing 检索一些值?如果有,怎么做?
    • 我只是在评估我将在 JavaScript 控制台中输入的内容并返回结果。因此,如果我在 JavaScript 控制台中序列化所有内容并只传递 JSON 对象应该没问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多