FireFox和Safari兼容event.path

問題的出現: 因爲在添加埋點的時候,給document綁定一個事件,而後循環e.path找出元素下的attribute的ilog,而後發送埋點。javascript

在項目開發中遇到須要獲取觸發事件元素冒泡過程的全部元素,在Chrome中能夠經過event.path獲取。html

element.onClick(event) {
  const ev = window.event || event; const path = ev.path; } 

該屬性在Chrome和Opera瀏覽器下沒問題,可是在Firefox和Safari中發現event並無path屬性。
進過查找資料發現,在瀏覽器新的標準裏定義了composedPath能夠獲取java

element.onClick(event) {
  const ev = window.event || event; const path = event.path || (event.composedPath && event.composedPath()); console.log(path) //[button#btn, div, body, html, document, Window] }


可是以上ios只支持10以上版本,爲了兼容ios9.X請看下面完整例子
* 獲取事件冒泡路徑,兼容ie11,edge,chrome,firefox,safari * @param evt * @returns {*} */

最總完整事件:
var ATTR_NAME = 'data-ilog';
var ATTR_BINDED = 'ilogbinded';
var location = window.location;

var getInnerText = function getInnerText(element) {
  return typeof element.textContent === 'string' ? element.textContent : element.innerText;
};
 

var eventPath = function eventPath(evt) {
  const path = (evt.composedPath && evt.composedPath()) || evt.path,
  target = evt.target;node

  if (path != null) {
    return (path.indexOf(window) < 0) ? path.concat(window) : path;
  }ios

  if (target === window) {
    return [window];
  }chrome

  function getParents(node, memo) {
    memo = memo || [];
    const parentNode = node.parentNode;瀏覽器

    if (!parentNode) {
      return memo;
    } else {
      return getParents(parentNode, memo.concat(parentNode));
    }
  }ui

  return [target].concat(getParents(target), window);
}spa

 
var bind = function bind(e) {
  var target;
   var path = eventPath(e);
  if(path && path.length>0){
  for (var i = 0; i < path.length; i++) {
    if (path[i].dataset && path[i].dataset.ilog) {
      target = path[i];
    }
  }
}
 
if (target) {
  var asm = target.getAttribute(ATTR_NAME);
  var isBinded = target.getAttribute(ATTR_BINDED);
  if (asm && isBinded === null) {
    var href = encodeURIComponent(location.href);
    var txt = getInnerText(target) + '';
    txt = txt.trim();
    // 發送埋點({ href: href, txt: txt, asm: asm })
  }
  return false;
  }
};
相關文章
相關標籤/搜索