列出PhantomJS中加载的页面的所有DOM事件

时间:2016-03-10 12:30:03

标签: javascript testing phantomjs

我想记录JS和html中绑定的所有事件。我目前的解决方案,它没有记录任何内容,我做错了什么,或者是否有更好的方法来捕获事件并保存其回调?

'use strict';
var page = require('webpage').create();

page.onConsoleMessage = function(msg) {
    console.log('CONSOLE: ' + msg);
};

page.open('url', function (status) {
    var _count = function() {
        return page.evaluate(function() {
            var htmlAddEventListener = HTMLElement.prototype.addEventListener;
            HTMLElement.prototype.addEventListener = function(name, cb) {
                console.log('1', name);
                this.boundEvents || (this.boundEvents = {});
                (this.boundEvents[name] || (this.boundEvents[name] = [])).push(cb);
                return htmlAddEventListener.apply(this, arguments);
            }
            var elementAddEventListener = Element.prototype.addEventListener;
            Element.prototype.addEventListener = function(name, cb) {
                console.log('1', name);
                this.boundEvents || (this.boundEvents = {});
                (this.boundEvents[name] || (this.boundEvents[name] = [])).push(cb);
                return elementAddEventListener.apply(this, arguments);
            }
            var documentAddEventListener = Document.prototype.addEventListener;
            Document.prototype.addEventListener = function(name, cb) {
                console.log('2', name);
                this.boundEvents || (this.boundEvents = {});
                (this.boundEvents[name] || (this.boundEvents[name] = [])).push(cb);
                return documentAddEventListener.apply(this, arguments);
            }
            var windowAddEventListener = window.addEventListener;
            window.addEventListener = function(name, cb) {
                console.log('3', name);
                this.boundEvents || (this.boundEvents = {});
                (this.boundEvents[name] || (this.boundEvents[name] = [])).push(cb);
                return windowAddEventListener.apply(this, arguments);
            }

            var elementDispatchEvent = Element.prototype.dispatchEvent;
            Element.prototype.dispatchEvent = function(name, cb) {
                console.log('1a', name);
                return elementDispatchEvent.apply(this, arguments);
            }
        });
    }
    _count();

});

1 个答案:

答案 0 :(得分:1)

在页面加载后,您正在更改内置对象原型中的各种addEventListener函数。在所有即时页面JavaScript运行后的大部分时间都会调用page.open回调。如果您加载的页面没有使用动态请求,则不会显示任何内容。

您应该在执行JavaScript页面之前从运行的事件处理程序中调用_count。示例包括page.onInitializedpage.onLoadStartedpage.onNavigationRequestedpage.onUrlChanged。确保你没有多次调用它。