FireFox和Safari兼容event.path


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

在項目開發中遇到需要獲取觸發事件元素冒泡過程的所有元素,在Chrome中可以通過event.path獲取。

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

該屬性在Chrome和Opera瀏覽器下沒問題,但是在Firefox和Safari中發現event並沒有path屬性。
進過查找資料發現,在瀏覽器新的標准里定義了composedPath可以獲取

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;

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

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

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

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

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

 
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;
  }
};
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM