在JavaScript中触发eventListeners

时间:2018-03-19 14:32:59

标签: javascript google-chrome google-chrome-extension

通过使用Chrome's API,我们可以使用函数

getEventListeners(object) 

获取某个DOM对象的所有eventListener。

现在如何在迭代后触发获取的mouseClick事件?

1 个答案:

答案 0 :(得分:1)

您可以随时创建和发送Event。请考虑以下示例。由于此代码段在浏览器上下文中运行,因此我们无法实际使用getEventListeners()



// Get an element
const test = document.querySelector(".test");

// Add a listener
test.addEventListener("click", () => console.log("test"));

// Trigger the listener
setTimeout(() => test.click(), 1000);

// Explicit event dispatching
setTimeout(() => {
  const evt = new Event("click");
  test.dispatchEvent(evt);
}, 2000);

// Create and dispatch events of every typ attached to element
if (typeof getEventListeners !== "function") {
  console.warn("getEventListeners is unsupported");
} else {
  Object.keys(getEventListeners(test)).forEach(k => {
    const e = new Event(k);
    test.dispatchEvent(e);
  });
}

<div class="test">Hello</div>
&#13;
&#13;
&#13;

因此,为了将所有这些归结为可重用的函数,我们可以写:

/**
 * Dispatch events for all listeners attached to an element
 * @param {Element} el The element to dispatch events for
 */
function fireAllListeners(el) {
  /* 
   * getEventListeners only works in console, so make 
   * sure we can call it without throwing an exception
   */
  if (typeof getEventListeners !== "function") {
    console.warn("getEventListeners is not supported in this context");
    return
  }

  // Get all the listeners on an element
  const listeners = getEventListeners(el);
  // Get all the types of listeners ("click", "touch", "load", etc)
  const listenerTypes = Object.keys(listeners);
  // Map those listeners and make events for each
  const eventsToFire = listenerTypes.map(lt => new Event(lt));

  // Dispatch all the events
  eventsToFire.forEach(e => el.dispatchEvent(e));
}