Is it possible to programmatically catch all events on the page in the browser?

前端 未结 7 512
心在旅途
心在旅途 2020-12-02 08:18

First of all, here is a list of event types that are defined by the W3C standards. (This list is based on the onevent attributes defined in the HTML5 standard. I assume that

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 08:40

    A bit late to the party but I did create something that might be useful for others here.

    https://codepen.io/phreaknation/pen/QmJjEa

    This is an ES6 Class that captures all events from an element that is known to that element. This demo allows you to change the element time in the page, as well as read out the events with clickable links to their MDN page as well as interact with the element and see how the events are triggered with time stamps.

    I hope this helps

    Class code

    class EventSystem {
      constructor(element) {
        this._ = {
          element: null
        }
    
        return this;
      }
    
      getAllEventTypes({blacklist = [], whitelist = []} = {}) {
        const events = [];
        for (let property in this._.element) {
          const match = property.match(/^on(.*)/);
          if (match) {
            if ((whitelist.length > 0 ? whitelist.indexOf(match) !== -1 : true) &&
                (blacklist.length > 0 ? blacklist.indexOf(match) === -1 : true)) {
              events.push(match[1]);
            }          
          }
        }
        return events;
      }
    
      getElementType() {
        return this._.element.tagName.toLowerCase();
      }
    
      setElement(element) {
        this._.element = element;
        return this;
      }
    
      applyEvents(events, callback) {
        events.forEach((event) => {
          this._.element.addEventListener(event, (ev) => {
            if (typeof callback === 'function') {
              callback(event, ev);
            }
          })
        })
      }
    }
    

提交回复
热议问题