Plugin Directory

Changeset 3011805


Ignore:
Timestamp:
12/19/2023 09:39:54 AM (2 years ago)
Author:
yuvalo
Message:

Update the supported version

Location:
goal-tracker-ga
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • goal-tracker-ga/tags/1.0.16/README.txt

    r2991535 r3011805  
    44Tags: analytics, events, wordpress, ga4
    55Requires at least: 5.5
    6 Tested up to: 6.3.2
     6Tested up to: 6.4.2
    77Stable tag: 1.0.16
    88Requires PHP: 5.6.20
  • goal-tracker-ga/trunk/README.txt

    r2991535 r3011805  
    44Tags: analytics, events, wordpress, ga4
    55Requires at least: 5.5
    6 Tested up to: 6.3.2
     6Tested up to: 6.4.2
    77Stable tag: 1.0.16
    88Requires PHP: 5.6.20
  • goal-tracker-ga/trunk/public/js/wp-goal-tracker-ga-public.js

    r2948161 r3011805  
    1 var __assign = (this && this.__assign) || function () {
    2     __assign = Object.assign || function(t) {
     1var __assign =
     2  (this && this.__assign) ||
     3  function () {
     4    __assign =
     5      Object.assign ||
     6      function (t) {
    37        for (var s, i = 1, n = arguments.length; i < n; i++) {
    4             s = arguments[i];
    5             for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
    6                 t[p] = s[p];
     8          s = arguments[i];
     9          for (var p in s)
     10            if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
    711        }
    812        return t;
     13      };
     14    return __assign.apply(this, arguments);
     15  };
     16var gtgaMainJs = (function ($) {
     17  "use strict";
     18  var _this = this;
     19  /**
     20   * Binds Download Tracking
     21   *
     22   * @returns {undefined}
     23   */
     24  var VideoPercent = {
     25    ZERO: 0,
     26    TWENTYFIVE: 25,
     27    FIFTY: 50,
     28    SEVENTYFIVE: 75,
     29    ONEHUNDRED: 100,
     30  };
     31  function elementAddedCallback(addedNode) {
     32    checkVisibilityEvents();
     33  }
     34  var observer = new MutationObserver(function (mutationsList) {
     35    mutationsList.forEach(function (mutation) {
     36      if (mutation.type === "childList") {
     37        Array.prototype.forEach.call(mutation.addedNodes, function (addedNode) {
     38          if (addedNode.nodeType === Node.ELEMENT_NODE) {
     39            elementAddedCallback(addedNode);
     40          }
     41        });
     42      }
     43    });
     44  });
     45  function getLinkClickParameters(event, url) {
     46    var tmpURL = new URL(url);
     47    var linkHostname = tmpURL.hostname;
     48    var linkEvent = {
     49      page_title: wpGoalTrackerGa.pageTitle,
     50      link_url: url,
     51      // page_location: window.location.href,
     52      outbound: isLinkExternal(url),
     53      link_domain: linkHostname,
     54      link_text: $(event.target).text(),
     55      link_classes: $(event.target).attr("class"),
    956    };
    10     return __assign.apply(this, arguments);
    11 };
    12 var gtgaMainJs = (function ($) {
    13     'use strict';
     57    return linkEvent;
     58  }
     59  var click_event = function (event) {
     60    trackCustomEvent(this, event.data.eventName, event.data.props);
     61    if (
     62      (typeof event.target.href !== "undefined" &&
     63        event.target.nodeName == "A") ||
     64      (typeof event.currentTarget.href !== "undefined" &&
     65        event.currentTarget.nodeName == "A")
     66    ) {
     67      if ($(event.target).parent().attr("role") !== "tab") {
     68        handleLinks(this, event);
     69      }
     70    }
     71  }; // End of click event function
     72  function bindEmailLinksTracking() {
     73    if (wpGoalTrackerGa.trackEmailLinks === "1") {
     74      $("body").on("click", 'a[href^="mailto:"]', function (e) {
     75        e.preventDefault();
     76        var email = this.href.split(":").pop();
     77        var page = getPageName();
     78        var eventParameters = {
     79          page_title: page,
     80          email_address: email,
     81          page_location: window.location.href,
     82          link_text: $(e.target).text(),
     83          link_classes: $(e.target).attr("class"),
     84        };
     85        trackCustomEvent(this, "email_link_click", eventParameters);
     86        handleLinks(this, e);
     87      });
     88    }
     89  }
     90  var isLinkExternal = function (url) {
     91    var query = new RegExp("//" + location.host + "($|/)");
     92    if (url.substring(0, 4) === "http") {
     93      if (!query.test(url)) {
     94        return true;
     95      }
     96    }
     97    return false;
     98  };
     99  var link_track_external = function (event) {
     100    var url = getUrl(event);
     101    if (typeof url !== "undefined" && url !== "") {
     102      if (isLinkExternal(url)) {
     103        link_track_all(event);
     104      }
     105    }
     106  };
     107  var link_track_external_new_tab = function (event) {
     108    var url = getUrl(event);
     109    if (isLinkExternal(url)) {
     110      var eventParameters = getLinkClickParameters(event, url);
     111      trackCustomEvent(this, "link_click", eventParameters);
     112    }
     113  };
     114  var link_track_all = function (event) {
     115    var url = getUrl(event);
     116    var hash = isJustHashLink(url);
     117    if (
     118      typeof url !== "undefined" &&
     119      url !== "" &&
     120      hash != "#" &&
     121      $(this).parent().attr("role") !== "tab"
     122    ) {
     123      var eventParameters = getLinkClickParameters(event, url);
     124      trackCustomEvent(this, "link_click", eventParameters);
     125      event.preventDefault();
     126      if (typeof hash !== "undefined" && hash !== "") {
     127        window.location.hash = hash;
     128      } else {
     129        setTimeout(function () {
     130          window.location.href = url;
     131        }, 250);
     132      }
     133    }
     134  };
     135  var link_track_all_new_tab = function (event) {
     136    var url = getUrl(event);
     137    if (typeof url !== "undefined" && url !== "") {
     138      var eventParameters = getLinkClickParameters(event, url);
     139      trackCustomEvent(this, "link_click", eventParameters);
     140    }
     141  };
     142  var handleLinks = function (self, event) {
     143    event.preventDefault();
     144    var link = getUrl(event);
     145    if (link === "") return;
     146    var w;
     147    var openInNewTab = isNewTab(self);
     148    if (openInNewTab) {
     149      w = window.open("", "_blank");
     150    }
     151    var hash = isJustHashLink(link);
     152    if (typeof hash !== "undefined" && hash !== "") {
     153      window.location.hash = hash;
     154    } else if (window.location.href !== link) {
     155      setTimeout(
     156        function () {
     157          if (openInNewTab) {
     158            w.location.href = link;
     159          } else {
     160            window.location.href = link;
     161          }
     162        },
     163        250,
     164        w
     165      );
     166    }
     167  };
     168  var getUrl = function (event) {
     169    var url = "";
     170    var $target = $(event.target);
     171    var $link = $target.closest("a");
     172    if ($link.length) {
     173      var href = $link.attr("href");
     174      if (href && href !== "#") {
     175        url = $link.prop("href");
     176      }
     177    }
     178    return url;
     179  };
     180  var isJustHashLink = function (url) {
     181    if (url.indexOf("#") === 0) {
     182      return url;
     183    }
     184    var currentUrl = new URL(window.location.href);
     185    var targetUrl = new URL(url, currentUrl);
     186    if (targetUrl.origin !== currentUrl.origin) {
     187      return "";
     188    }
     189    if (
     190      targetUrl.pathname === currentUrl.pathname &&
     191      targetUrl.search === currentUrl.search &&
     192      targetUrl.hash !== ""
     193    ) {
     194      return targetUrl.hash;
     195    }
     196    return "";
     197  };
     198  var isNewTab = function (self) {
     199    var target = $(self).attr("target");
     200    if (typeof target !== "undefined" && target.trim() === "_blank") {
     201      return true;
     202    }
     203    return false;
     204  };
     205  $(document).ready(function () {
     206    var targetNode = document.body;
     207    var config = { childList: true, subtree: true };
     208    observer.observe(targetNode, config);
     209    $(window).on("scroll", checkVisibilityEvents);
     210    // We also want to check it when
     211    checkVisibilityEvents();
     212    if (wpGoalTrackerGa.trackEmailLinks) {
     213      bindEmailLinksTracking();
     214    }
     215    // Bind link tracking events
     216    if (wpGoalTrackerGa.trackLinks.enabled) {
     217      if (wpGoalTrackerGa.trackLinks.type === "all") {
     218        $("body").on("click", 'a:not([target~="_blank"])', link_track_all);
     219        $("body").on("click", 'a[target~="_blank"]', link_track_all_new_tab);
     220      } else if (wpGoalTrackerGa.trackLinks.type === "external") {
     221        $("body").on("click", 'a:not([target~="_blank"])', link_track_external);
     222        $("body").on(
     223          "click",
     224          'a[target~="_blank"]',
     225          link_track_external_new_tab
     226        );
     227      }
     228    }
     229    wpGoalTrackerGa.click.forEach(function (el) {
     230      var selector = makeSelector(el);
     231      $("body").on("click", selector, el, click_event);
     232    });
     233  });
     234  function makeSelector(click_option) {
     235    var selector = "";
     236    if (click_option.selectorType === "class") {
     237      selector += ".";
     238    } else if (click_option.selectorType === "id") {
     239      selector += "#";
     240    }
     241    selector += click_option.selector;
     242    return selector;
     243  }
     244  function checkVisibilityEvents() {
     245    // TO DO this code can be simplified a lot. May be better to use
     246    // $('element').visibility()
     247    var ga_window = $(window).height();
     248    var ga_visibility_top = $(document).scrollTop();
     249    for (var i = 0; i < wpGoalTrackerGa.visibility.length; i++) {
     250      if (!wpGoalTrackerGa.visibility[i].sent) {
     251        // NB was unescapeChars( wpGoalTrackerGa.visibility[i].select)
     252        var $select = $(makeSelector(wpGoalTrackerGa.visibility[i]));
     253        wpGoalTrackerGa.visibility[i].offset = $select.offset();
     254        if (
     255          wpGoalTrackerGa.visibility[i].offset &&
     256          ga_visibility_top + ga_window >=
     257            wpGoalTrackerGa.visibility[i].offset.top + $select.height()
     258        ) {
     259          trackCustomEvent(
     260            $select,
     261            wpGoalTrackerGa.visibility[i].eventName,
     262            wpGoalTrackerGa.visibility[i].props
     263          );
     264          wpGoalTrackerGa.visibility[i].sent = true;
     265        }
     266      }
     267    }
     268  } // End of bindVisibilityEvents
     269  var trackCustomEventBasic = function (self, name, props) {
     270    Object.keys(props).forEach(function (key) {
     271      props[key] = prepareProps(self, props[key]);
     272    });
     273    gtag("event", name, __assign({}, props));
     274  };
     275  /* <fs_premium_only> */
     276  /* ---------------------------------------------------------------- */
     277  var trackCustomEventPro = function (self, name, props) {
     278    // We don't want to override the original object.
     279    var propsCopy = __assign({}, props);
     280    Object.keys(propsCopy).forEach(function (key) {
     281      propsCopy[key] = prepareProps(self, propsCopy[key]);
     282    });
     283    if (typeof gtgatag !== "undefined") {
     284      gtgatag("event", name, propsCopy);
     285    } else if (typeof gtag !== "undefined") {
     286      gtag("event", name, propsCopy);
     287    }
     288  };
     289  var onPlayerReady = function () {};
     290  var youtube_video_instances = [];
     291  var youTubeApiIsReady = false;
     292  var youTubeApiCallbacks = [];
     293  function whenYouTubeApiReady(callback) {
     294    if (youTubeApiIsReady) {
     295      callback();
     296    } else {
     297      youTubeApiCallbacks.push(callback);
     298    }
     299  }
     300  function register_youtube_video(video) {
     301    whenYouTubeApiReady(function () {
     302      // YouTube API is ready, you can now register the video
     303      youtube_video_instances.push(
     304        new YT.Player(video, {
     305          events: {
     306            onReady: onPlayerReady,
     307            onStateChange: onPlayerStateChange,
     308            onPlaybackQualityChange: onPlaybackQualityChange,
     309          },
     310        })
     311      );
     312    });
     313  }
     314  // Tracking YouTube Porgress using interval checking.
     315  function trackYouTubeProgress(player) {
     316    var mediaDuration = player.getDuration();
     317    var timeoutDuration = (mediaDuration * 1000) / 20;
     318    var count = 0;
     319    var eventsSent = [];
     320    var durationInterval = setInterval(function () {
     321      if (player.getPlayerState() === 1) {
     322        count += 1;
     323        var currentPos = (player.getCurrentTime() / mediaDuration) * 100;
     324        var roundedPos = getVideoPosition(currentPos, eventsSent);
     325        eventsSent[roundedPos] = true;
     326        if (roundedPos !== 0) {
     327          var videoData = player.getVideoData();
     328          var eventData = {
     329            video_current_time: player.getCurrentTime(),
     330            video_duration: player.getDuration(),
     331            video_percent: roundedPos,
     332            video_title: videoData.title,
     333            video_url: player.getVideoUrl(),
     334            video_provider: "youtube",
     335          };
     336          trackCustomEvent(this, "video_progress", eventData);
     337        }
     338      } else {
     339        clearInterval(durationInterval);
     340      }
     341      if (count >= 21 || eventsSent[75]) {
     342        clearInterval(durationInterval);
     343      }
     344    }, timeoutDuration);
     345  }
     346  // youtube video player
     347  function onPlayerStateChange(event) {
     348    var videoData = event.target.getVideoData();
     349    var iframe = event.target.getIframe();
     350    var player = event.target;
     351    var playerStatus = player.getPlayerState();
     352    if (
     353      event.data === YT.PlayerState.PLAYING ||
     354      playerStatus === YT.PlayerState.PLAYING
     355    ) {
     356      // Start tracking video progress.
     357      trackYouTubeProgress(player);
     358      // Send out a video_start event
     359      var eventData = {
     360        video_current_time: 0,
     361        video_duration: player.getDuration(),
     362        video_percent: VideoPercent.ZERO,
     363        video_title: videoData.title,
     364        video_url: player.getVideoUrl(),
     365        video_provider: "youtube",
     366      };
     367      trackCustomEvent(this, "video_start", eventData);
     368    } else if (event.data === YT.PlayerState.ENDED) {
     369      // if (wpGoalTrackerGa.youTubeVideosFromDB[iframe.id].trackEnd === "true") {
     370      var eventData = {
     371        video_current_time: player.getDuration(),
     372        video_duration: player.getDuration(),
     373        video_percent: VideoPercent.ONEHUNDRED,
     374        video_title: videoData.title,
     375        video_url: player.getVideoUrl(),
     376        video_provider: "youtube",
     377      };
     378      trackCustomEvent(this, "video_complete", eventData);
     379      // }
     380    } else if (event.data === YT.PlayerState.PAUSED) {
     381      // if (wpGoalTrackerGa.youTubeVideosFromDB[iframe.id].trackPause === "true") {
     382      // trackCustomEvent("YouTube", "Paused", videoData.title, false);
     383      // }
     384    }
     385  }
     386  function onPlaybackQualityChange(event) {
     387    var iframe = event.target.getIframe();
     388  }
     389  // get youtube id from src
     390  var youtube_src_parser = function (url) {
     391    var regExp =
     392      /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
     393    var match = url.match(regExp);
     394    return match && match[7].length === 11 ? match[7] : false;
     395  };
     396  // get vimeo id from src
     397  var vimeo_src_parser = function (url) {
     398    var regExp = /(videos|video|channels|\.com)\/([\d]+)/;
     399    var match = url.match(regExp)[2];
     400    return match ? match : false;
     401  };
     402  // add url param
     403  var add_params_to_url = function (url, param) {
     404    var new_url;
     405    if (-1 === url.indexOf("?")) {
     406      new_url = url + "?" + param;
     407    } else {
     408      new_url = url + "&" + param;
     409    }
     410    return new_url;
     411  };
     412  function check_for_vimeo_videos() {
     413    var iframes = document.querySelectorAll("iframe");
     414    iframes.forEach(function (iframe) {
     415      var src = iframe.getAttribute("src");
     416      var dataLazySrc = iframe.getAttribute("data-lazy-src");
     417      var dataSrc = iframe.getAttribute("data-src");
     418      if (src && src.includes("vimeo.com")) {
     419        var vimeo_id = vimeo_src_parser(src);
     420        $(iframe).attr("id", vimeo_id); //force replace the iframe ID with the vimeo_id
     421        register_vimeo_video(vimeo_id);
     422      } else if (dataLazySrc || dataSrc) {
     423        // set a timer to wait for iframe to load
     424        var intervalId_1 = setInterval(function () {
     425          var newSrc = iframe.getAttribute("src"); // get the updated src attribute
     426          var newDataLazySrc = iframe.getAttribute("data-lazy-src"); // get the updated data-lazy-src attribute
     427          var newDataSrc = iframe.getAttribute("data-src"); // get the updated data-lazy-src attribute
     428          if (newSrc && newSrc.includes("vimeo.com")) {
     429            // `src` attribute has been set, register the video
     430            var vimeo_id = vimeo_src_parser(newSrc);
     431            $(iframe).attr("id", vimeo_id); //force replace the iframe ID with the vimeo_id
     432            register_vimeo_video(vimeo_id);
     433            // clear the interval
     434            clearInterval(intervalId_1);
     435          } else if (!newDataLazySrc && !newDataSrc) {
     436            // data-lazy-src attribute is no longer present, clear the interval
     437            clearInterval(intervalId_1);
     438          }
     439        }, 1000); // check every 1 second
     440      }
     441    });
     442  }
     443  // check for videos that do not have iframe id, origin or jsapi
     444  function check_for_youtube_videos() {
     445    var iframes = document.querySelectorAll("iframe");
     446    iframes.forEach(function (iframe) {
     447      var src = iframe.getAttribute("src");
     448      var dataLazySrc = iframe.getAttribute("data-lazy-src");
     449      var dataSrc = iframe.getAttribute("data-src");
     450      if (src && src.includes("youtube.com")) {
     451        // Regular case: src is already set
     452        registerAndModifyIframe(iframe, src);
     453      } else if (dataLazySrc || dataSrc) {
     454        // Lazy loading case: set an interval to check for iframe src updates
     455        var intervalId_2 = setInterval(function () {
     456          var newSrc = iframe.getAttribute("src");
     457          if (newSrc && newSrc.includes("youtube.com")) {
     458            registerAndModifyIframe(iframe, newSrc);
     459            clearInterval(intervalId_2); // Clear the interval once we've found and registered the video
     460          }
     461        }, 1000); // Check every second
     462      }
     463    });
     464  }
     465  function registerAndModifyIframe(iframe, src) {
     466    var youtube_id = youtube_src_parser(src);
     467    var new_iframe_src = src;
     468    // Check and set iframe ID if missing
     469    if (!iframe.id) {
     470      iframe.id = youtube_id;
     471    }
     472    // Check and set jsapi parameter if missing
     473    if (src.indexOf("jsapi") === -1) {
     474      new_iframe_src = add_params_to_url(new_iframe_src, "enablejsapi=1");
     475    }
     476    // Check and set origin parameter if missing
     477    if (src.indexOf("origin") === -1) {
     478      var originValue =
     479        window.location.protocol + "//" + window.location.hostname;
     480      if (window.location.port) {
     481        originValue += ":" + window.location.port;
     482      }
     483      new_iframe_src = add_params_to_url(
     484        new_iframe_src,
     485        "origin=" + originValue
     486      );
     487    }
     488    // Update iframe src if it was modified
     489    if (new_iframe_src !== src) {
     490      iframe.src = new_iframe_src;
     491    }
     492    // Register the video for tracking
     493    register_youtube_video(youtube_id);
     494  }
     495  function register_vimeo_video(video) {
     496    var vimeo_player = new Vimeo.Player(video);
     497    vimeo_player.gtgaVideoPercentSent = [];
     498    vimeo_player.on("play", vimeoOnPlay);
     499    vimeo_player.on("ended", vimeoOnEnd);
     500    vimeo_player.on("timeupdate", vimeoOnTimeUpdate);
     501  }
     502  function vimeoOnTimeUpdate(event) {
    14503    var _this = this;
    15     /**
    16      * Binds Download Tracking
    17      *
    18      * @returns {undefined}
    19      */
    20     var VideoPercent = {
    21         ZERO: 0,
    22         TWENTYFIVE: 25,
    23         FIFTY: 50,
    24         SEVENTYFIVE: 75,
    25         ONEHUNDRED: 100,
     504    var percent = 0;
     505    var roundedPercent = event.percent * 100;
     506    if (roundedPercent > 75 && !this.gtgaVideoPercentSent[75]) {
     507      percent = 75;
     508    } else if (roundedPercent > 50 && !this.gtgaVideoPercentSent[50]) {
     509      percent = 50;
     510    } else if (roundedPercent > 25 && !this.gtgaVideoPercentSent[25]) {
     511      percent = 25;
     512    } else if (roundedPercent > 10 && !this.gtgaVideoPercentSent[10]) {
     513      percent = 10;
     514    } else {
     515      return;
     516    }
     517    if (percent != 0) {
     518      var videoDuration = event.duration;
     519      var vimeoEvent_1 = {
     520        video_current_time: event.seconds,
     521        video_duration: videoDuration,
     522        video_title: "",
     523        video_percent: percent,
     524        video_provider: "vimeo",
     525        video_url: "",
     526      };
     527      this.getVideoTitle().then(function (title) {
     528        vimeoEvent_1.video_title = title;
     529        _this.getVideoUrl().then(function (url) {
     530          vimeoEvent_1.video_url = url;
     531          trackCustomEvent(_this, "video_progress", vimeoEvent_1);
     532          _this.gtgaVideoPercentSent[percent] = true;
     533        });
     534      });
     535    }
     536  }
     537  function vimeoOnPlay(event) {
     538    var _this = this;
     539    var videoDuration = event.duration;
     540    var vimeoEvent = {
     541      video_current_time: 0,
     542      video_duration: videoDuration,
     543      video_title: "",
     544      video_percent: 0,
     545      video_provider: "vimeo",
     546      video_url: "",
    26547    };
    27     function elementAddedCallback(addedNode) {
    28         checkVisibilityEvents();
    29     }
    30     var observer = new MutationObserver(function (mutationsList) {
    31         mutationsList.forEach(function (mutation) {
    32             if (mutation.type === 'childList') {
    33                 Array.prototype.forEach.call(mutation.addedNodes, function (addedNode) {
    34                     if (addedNode.nodeType === Node.ELEMENT_NODE) {
    35                         elementAddedCallback(addedNode);
    36                     }
    37                 });
     548    this.getVideoTitle().then(function (title) {
     549      vimeoEvent.video_title = title;
     550      _this.getVideoUrl().then(function (url) {
     551        vimeoEvent.video_url = url;
     552        trackCustomEvent(_this, "video_start", vimeoEvent);
     553      });
     554    });
     555  }
     556  function vimeoOnEnd(event) {
     557    var _this = this;
     558    var videoDuration = event.duration;
     559    var vimeoEvent = {
     560      video_current_time: videoDuration,
     561      video_duration: videoDuration,
     562      video_title: "",
     563      video_percent: 100,
     564      video_provider: "vimeo",
     565      video_url: "",
     566    };
     567    this.getVideoTitle().then(function (title) {
     568      vimeoEvent.video_title = title;
     569      _this.getVideoUrl().then(function (url) {
     570        vimeoEvent.video_url = url;
     571        trackCustomEvent(_this, "video_complete", vimeoEvent);
     572      });
     573    });
     574  }
     575  ////////////////////////////////////////////////////////
     576  ///// Self Hosted Media Tracking                                        //
     577  ////////////////////////////////////////////////////////
     578  function capitalizeFirstLetter(word) {
     579    return word.charAt(0).toUpperCase() + word.slice(1);
     580  }
     581  function getMediaFileName(e) {
     582    if (typeof e.target !== "undefined" && e.target.currentSrc) {
     583      return e.target.currentSrc.replace(/^.*[\\\/]/, "");
     584    } else if (typeof e.target !== "undefined" && e.target.src) {
     585      return e.target.src.replace(/^.*[\\\/]/, "");
     586    }
     587    return "";
     588  }
     589  function getMediaEvent(type, currentTime, duration, title, percent, url) {
     590    if (type === "video") {
     591      var mediaEvent = {
     592        video_current_time: currentTime,
     593        video_duration: duration,
     594        video_title: title,
     595        video_percent: percent,
     596        video_provider: "self_hosted",
     597        video_url: url,
     598      };
     599      return mediaEvent;
     600    }
     601    if (type === "audio") {
     602      var mediaEvent = {
     603        audio_current_time: currentTime,
     604        audio_duration: duration,
     605        audio_title: title,
     606        audio_percent: percent,
     607        audio_provider: "self_hosted",
     608        audio_url: url,
     609      };
     610      return mediaEvent;
     611    }
     612    return;
     613  }
     614  function register_media_tracking(type) {
     615    if (
     616      (type === "video" &&
     617        typeof wpGoalTrackerGa.videoSettings.gaMediaVideoTracking !==
     618          "undefined") ||
     619      (type === "audio" &&
     620        typeof wpGoalTrackerGa.videoSettings.gaMediaAudioTracking)
     621    ) {
     622      document.addEventListener(
     623        "play",
     624        function (e) {
     625          if (e.target.tagName === type.toUpperCase()) {
     626            var url = e.target.currentSrc;
     627            var title = getMediaFileName(e);
     628            var duration = e.target.duration;
     629            var mediaEvent = getMediaEvent(type, 0, duration, title, 0, url);
     630            trackCustomEvent(this, type + "_start", mediaEvent);
     631          }
     632        },
     633        true
     634      );
     635      document.addEventListener(
     636        "ended",
     637        function (e) {
     638          if (e.target.tagName === type.toUpperCase()) {
     639            var url = e.target.currentSrc;
     640            var title = getMediaFileName(e);
     641            var duration = e.target.duration;
     642            var mediaEvent = getMediaEvent(
     643              type,
     644              duration,
     645              duration,
     646              title,
     647              100,
     648              url
     649            );
     650            trackCustomEvent(this, type + "_complete", mediaEvent);
     651          }
     652        },
     653        true
     654      );
     655      document.addEventListener(
     656        "timeupdate",
     657        function (e) {
     658          if (e.target.tagName === type.toUpperCase()) {
     659            if (typeof e.target.progressSent === "undefined") {
     660              e.target.progressSent = [];
    38661            }
    39         });
    40     });
    41     function getLinkClickParameters(event, url) {
    42         var tmpURL = new URL(url);
    43         var linkHostname = tmpURL.hostname;
    44         var linkEvent = {
    45             page_title: wpGoalTrackerGa.pageTitle,
    46             link_url: url,
    47             // page_location: window.location.href,
    48             outbound: isLinkExternal(url),
    49             link_domain: linkHostname,
    50             link_text: $(event.target).text(),
    51             link_classes: $(event.target).attr('class'),
     662            var media = e.target;
     663            var mediaDuration = e.target.duration;
     664            var currentPos = (media.currentTime / mediaDuration) * 100;
     665            var roundedPos = getVideoPosition(
     666              currentPos,
     667              e.target.progressSent
     668            );
     669            if (roundedPos !== 0) {
     670              e.target.progressSent[roundedPos] = true;
     671              var url = e.target.currentSrc;
     672              var title = getMediaFileName(e);
     673              var currentTime = e.target.currentTime;
     674              var duration = e.target.duration;
     675              var mediaEvent = getMediaEvent(
     676                type,
     677                currentTime,
     678                duration,
     679                title,
     680                roundedPos,
     681                url
     682              );
     683              trackCustomEvent(this, type + "_progress", mediaEvent);
     684            }
     685          }
     686        },
     687        true
     688      );
     689    }
     690  }
     691  ////////////////////////////////////////////////////////////////
     692  ////////////////////////////////////////////////////////////////
     693  ////// Handle Placeholders                                                     ///////////
     694  ////////////////////////////////////////////////////////////////
     695  function get_placeholder(self, placeholder) {
     696    if (typeof placeholder === "undefined") {
     697      return "";
     698    }
     699    var el = placeholder;
     700    var lel = "";
     701    if (typeof el.indexOf !== "function") {
     702      return placeholder;
     703    }
     704    if (el.indexOf("$$PAGENAME$$") > -1) {
     705      if (true === wpGoalTrackerGa.isFrontPage) {
     706        el = replace_with(el, "$$PAGENAME$$", "Home page");
     707      } else {
     708        el = replace_with(el, "$$PAGENAME$$", wpGoalTrackerGa.pageTitle);
     709      }
     710    }
     711    if (el.indexOf("$$POST_ID$$") > -1) {
     712      el = replace_with(el, "$$POST_ID$$", wpGoalTrackerGa.postID);
     713    }
     714    if (el.indexOf("$$CATEGORY$$") > -1) {
     715      el = replace_with(el, "$$CATEGORY$$", wpGoalTrackerGa.category);
     716    }
     717    if (el.indexOf("$$ATTR_") > -1) {
     718      var attr = "";
     719      var regex = /\$\$ATTR_(.*)\$\$/g;
     720      var match = regex.exec(el);
     721      if (typeof match[1] !== "undefined") {
     722        attr = match[1].toLowerCase();
     723      }
     724      lel = $(this).attr(attr);
     725      if (typeof lel === "undefined") {
     726        lel = $(self).attr(attr);
     727      }
     728      el = replace_with(el, match[0], lel);
     729    }
     730    if (el.indexOf("$$ELEMENT_TEXT$$") > -1) {
     731      el = replace_with(el, "$$ELEMENT_TEXT$$", $(self).text());
     732    }
     733    if (el.indexOf("$$AUTHOR$$") > -1) {
     734      el = replace_with(el, "$$AUTHOR$$", wpGoalTrackerGa.postAuthor);
     735    }
     736    if (el.indexOf("$$REFERRER$$") > -1) {
     737      var referrer = document.referrer;
     738      if (referrer === "") {
     739        referrer = window.location.href;
     740      }
     741      el = replace_with(el, "$$REFERRER$$", referrer);
     742    }
     743    if (el.indexOf("$$USER$$") > -1) {
     744      if (0 === wpGoalTrackerGa.currentUserName) {
     745        lel = "Guest";
     746      } else {
     747        lel = wpGoalTrackerGa.currentUserName;
     748      }
     749      el = replace_with(el, "$$USER$$", lel);
     750    }
     751    if (el.indexOf("$$PAGE_URL$$") > -1) {
     752      el = window.location.href;
     753    }
     754    if (el.indexOf("$$IS_LOGGED_IN$$") > -1) {
     755      if (
     756        typeof wpGoalTrackerGa.isUserLoggedIn !== "undefined" &&
     757        wpGoalTrackerGa.isUserLoggedIn === "1"
     758      ) {
     759        el = "true";
     760      } else {
     761        el = "false";
     762      }
     763    }
     764    if (el.indexOf("$$USER_ID$$") > -1) {
     765      if (typeof wpGoalTrackerGa.currentUserId !== "undefined") {
     766        el = wpGoalTrackerGa.currentUserId;
     767      } else {
     768        el = "";
     769      }
     770    }
     771    return el;
     772  }
     773  var replace_with = function (el, search, updated) {
     774    return el.replace(search, updated);
     775  };
     776  var sendQueuedEvents = function () {
     777    if (
     778      typeof wpGoalTrackerGaEvents !== "undefined" &&
     779      typeof wpGoalTrackerGaEvents.pending !== "undefined"
     780    ) {
     781      Object.keys(wpGoalTrackerGaEvents.pending).forEach(function (key) {
     782        trackCustomEvent(this, key, wpGoalTrackerGaEvents.pending[key]);
     783      });
     784    }
     785  };
     786  $(document).ready(function () {
     787    sendQueuedEvents();
     788    if (
     789      wpGoalTrackerGa.hasOwnProperty("videoSettings") &&
     790      (wpGoalTrackerGa.videoSettings.gaMediaAudioTracking ||
     791        wpGoalTrackerGa.videoSettings.gaMediaVideoTracking ||
     792        wpGoalTrackerGa.videoSettings.gaVimeoVideoTracking ||
     793        wpGoalTrackerGa.videoSettings.gaYoutubeVideoTracking)
     794    ) {
     795      if (wpGoalTrackerGa.videoSettings.gaYoutubeVideoTracking) {
     796        var tag = document.createElement("script");
     797        tag.src = "//www.youtube.com/iframe_api";
     798        var firstScriptTag = document.getElementsByTagName("script")[0];
     799        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
     800        window.onYouTubeIframeAPIReady = function () {
     801          youTubeApiIsReady = true;
     802          for (var i = 0; i < youTubeApiCallbacks.length; i++) {
     803            youTubeApiCallbacks[i]();
     804          }
     805          youTubeApiCallbacks = []; // Clear out callbacks once executed.
    52806        };
    53         return linkEvent;
    54     }
    55     var click_event = function (event) {
    56         trackCustomEvent(this, event.data.eventName, event.data.props);
    57         if ((typeof event.target.href !== 'undefined' &&
    58             event.target.nodeName == 'A') ||
    59             (typeof event.currentTarget.href !== 'undefined' &&
    60                 event.currentTarget.nodeName == 'A')) {
    61             handleLinks(this, event);
    62         }
    63     }; // End of click event function
    64     function bindEmailLinksTracking() {
    65         if (wpGoalTrackerGa.trackEmailLinks === '1') {
    66             $('body').on('click', 'a[href^="mailto:"]', function (e) {
    67                 e.preventDefault();
    68                 var email = this.href.split(':').pop();
    69                 var page = getPageName();
    70                 var eventParameters = {
    71                     page_title: page,
    72                     email_address: email,
    73                     page_location: window.location.href,
    74                     link_text: $(e.target).text(),
    75                     link_classes: $(e.target).attr('class'),
    76                 };
    77                 trackCustomEvent(this, 'email_link_click', eventParameters);
    78                 handleLinks(this, e);
    79             });
    80         }
    81     }
    82     var isLinkExternal = function (url) {
    83         var query = new RegExp('//' + location.host + '($|/)');
    84         if (url.substring(0, 4) === 'http') {
    85             if (!query.test(url)) {
    86                 return true;
    87             }
    88         }
    89         return false;
    90     };
    91     var link_track_external = function (event) {
    92         var url = getUrl(event);
    93         if (typeof url !== 'undefined' && url !== '') {
    94             if (isLinkExternal(url)) {
    95                 link_track_all(event);
    96             }
    97         }
    98     };
    99     var link_track_external_new_tab = function (event) {
    100         var url = getUrl(event);
    101         if (isLinkExternal(url)) {
    102             var eventParameters = getLinkClickParameters(event, url);
    103             trackCustomEvent(this, 'link_click', eventParameters);
    104         }
    105     };
    106     var link_track_all = function (event) {
    107         var url = getUrl(event);
    108         var hash = isJustHashLink(url);
    109         if (typeof url !== 'undefined' &&
    110             url !== '' &&
    111             hash != '#' &&
    112             $(this).parent().attr('role') !== 'tab') {
    113             var eventParameters = getLinkClickParameters(event, url);
    114             trackCustomEvent(this, 'link_click', eventParameters);
    115             event.preventDefault();
    116             if (typeof hash !== 'undefined' && hash !== '') {
    117                 window.location.hash = hash;
    118             }
    119             else {
    120                 setTimeout(function () {
    121                     window.location.href = url;
    122                 }, 250);
    123             }
    124         }
    125     };
    126     var link_track_all_new_tab = function (event) {
    127         var url = getUrl(event);
    128         if (typeof url !== 'undefined' && url !== '') {
    129             var eventParameters = getLinkClickParameters(event, url);
    130             trackCustomEvent(this, 'link_click', eventParameters);
    131         }
    132     };
    133     var handleLinks = function (self, event) {
    134         event.preventDefault();
    135         var link = getUrl(event);
    136         if (link === '')
    137             return;
    138         var w;
    139         var openInNewTab = isNewTab(self);
    140         if (openInNewTab) {
    141             w = window.open('', '_blank');
    142         }
    143         var hash = isJustHashLink(link);
    144         if (typeof hash !== 'undefined' && hash !== '') {
    145             window.location.hash = hash;
    146         }
    147         else if (window.location.href !== link) {
    148             setTimeout(function () {
    149                 if (openInNewTab) {
    150                     w.location.href = link;
    151                 }
    152                 else {
    153                     window.location.href = link;
    154                 }
    155             }, 250, w);
    156         }
    157     };
    158     var getUrl = function (event) {
    159         var url = '';
    160         var $target = $(event.target);
    161         var $link = $target.closest('a');
    162         if ($link.length) {
    163             var href = $link.attr('href');
    164             if (href && href !== '#') {
    165                 url = $link.prop('href');
    166             }
    167         }
    168         return url;
    169     };
    170     var isJustHashLink = function (url) {
    171         if (url.indexOf('#') === 0) {
    172             return url;
    173         }
    174         var currentUrl = new URL(window.location.href);
    175         var targetUrl = new URL(url, currentUrl);
    176         if (targetUrl.origin !== currentUrl.origin) {
    177             return '';
    178         }
    179         if (targetUrl.pathname === currentUrl.pathname &&
    180             targetUrl.search === currentUrl.search &&
    181             targetUrl.hash !== '') {
    182             return targetUrl.hash;
    183         }
    184         return '';
    185     };
    186     var isNewTab = function (self) {
    187         var target = $(self).attr('target');
    188         if (typeof target !== 'undefined' && target.trim() === '_blank') {
    189             return true;
    190         }
    191         return false;
    192     };
    193     $(document).ready(function () {
    194         var targetNode = document.body;
    195         var config = { childList: true, subtree: true };
    196         observer.observe(targetNode, config);
    197         $(window).on('scroll', checkVisibilityEvents);
    198         // We also want to check it when
    199         checkVisibilityEvents();
    200         if (wpGoalTrackerGa.trackEmailLinks) {
    201             bindEmailLinksTracking();
    202         }
    203         // Bind link tracking events
    204         if (wpGoalTrackerGa.trackLinks.enabled) {
    205             if (wpGoalTrackerGa.trackLinks.type === 'all') {
    206                 $('body').on('click', 'a:not([target~="_blank"])', link_track_all);
    207                 $('body').on('click', 'a[target~="_blank"]', link_track_all_new_tab);
    208             }
    209             else if (wpGoalTrackerGa.trackLinks.type === 'external') {
    210                 $('body').on('click', 'a:not([target~="_blank"])', link_track_external);
    211                 $('body').on('click', 'a[target~="_blank"]', link_track_external_new_tab);
    212             }
    213         }
    214         wpGoalTrackerGa.click.forEach(function (el) {
    215             var selector = makeSelector(el);
    216             $('body').on('click', selector, el, click_event);
    217         });
    218     });
    219     function makeSelector(click_option) {
    220         var selector = '';
    221         if (click_option.selectorType === 'class') {
    222             selector += '.';
    223         }
    224         else if (click_option.selectorType === 'id') {
    225             selector += '#';
    226         }
    227         selector += click_option.selector;
    228         return selector;
    229     }
    230     function checkVisibilityEvents() {
    231         // TO DO this code can be simplified a lot. May be better to use
    232         // $('element').visibility()
    233         var ga_window = $(window).height();
    234         var ga_visibility_top = $(document).scrollTop();
    235         for (var i = 0; i < wpGoalTrackerGa.visibility.length; i++) {
    236             if (!wpGoalTrackerGa.visibility[i].sent) {
    237                 // NB was unescapeChars( wpGoalTrackerGa.visibility[i].select)
    238                 var $select = $(makeSelector(wpGoalTrackerGa.visibility[i]));
    239                 wpGoalTrackerGa.visibility[i].offset = $select.offset();
    240                 if (wpGoalTrackerGa.visibility[i].offset &&
    241                     ga_visibility_top + ga_window >=
    242                         wpGoalTrackerGa.visibility[i].offset.top + $select.height()) {
    243                     trackCustomEvent($select, wpGoalTrackerGa.visibility[i].eventName, wpGoalTrackerGa.visibility[i].props);
    244                     wpGoalTrackerGa.visibility[i].sent = true;
    245                 }
    246             }
    247         }
    248     } // End of bindVisibilityEvents
    249     var trackCustomEventBasic = function (self, name, props) {
    250         Object.keys(props).forEach(function (key) {
    251             props[key] = prepareProps(self, props[key]);
    252         });
    253         gtag('event', name, __assign({}, props));
    254     };
    255    
    256     function returnOriginalProp(self, prop) {
    257         return prop;
    258     }
    259     function getPageName() {
    260         if ('1' === wpGoalTrackerGa.isFrontPage) {
    261             return 'Home';
    262         }
    263         else {
    264             if (typeof wpGoalTrackerGa.pageTitle !== 'undefined') {
    265                 return wpGoalTrackerGa.pageTitle;
    266             }
    267         }
    268         return '';
    269     }
    270     var trackCustomEvent = typeof trackCustomEventPro === 'function'
    271         ? trackCustomEventPro
    272         : trackCustomEventBasic;
    273     var prepareProps = typeof get_placeholder === 'function'
    274         ? get_placeholder
    275         : returnOriginalProp;
    276     return { isJustHashLink: isJustHashLink };
     807        check_for_youtube_videos();
     808      }
     809      check_for_vimeo_videos();
     810      if (wpGoalTrackerGa.videoSettings.gaMediaVideoTracking) {
     811        register_media_tracking("video");
     812      }
     813      if (wpGoalTrackerGa.videoSettings.gaMediaAudioTracking) {
     814        register_media_tracking("audio");
     815      }
     816    }
     817  });
     818  // }
     819  ////////////////////////////////////////////////////////////////
     820  ////// Contact Form 7                                                          ///////////
     821  ////////////////////////////////////////////////////////////////
     822  if (gtgaContactForm7Enabled()) {
     823    if (
     824      wpGoalTrackerGa.formTrackingSettings.contactForm7Settings.trackFormSubmit
     825    ) {
     826      document.addEventListener(
     827        "wpcf7submit",
     828        function (event) {
     829          var eventData = gtgaGetContactForm7EventData(event);
     830          trackCustomEvent(_this, "wpcf7_button_click", eventData);
     831        },
     832        false
     833      );
     834    }
     835    if (
     836      wpGoalTrackerGa.formTrackingSettings.contactForm7Settings.trackMailSent
     837    ) {
     838      document.addEventListener(
     839        "wpcf7mailsent",
     840        function (event) {
     841          var eventData = gtgaGetContactForm7EventData(event);
     842          trackCustomEvent(_this, "wpcf7_submission", eventData);
     843        },
     844        false
     845      );
     846    }
     847    if (
     848      wpGoalTrackerGa.formTrackingSettings.contactForm7Settings.trackMailFailed
     849    ) {
     850      document.addEventListener(
     851        "wpcf7mailfailed",
     852        function (event) {
     853          var eventData = gtgaGetContactForm7EventData(event);
     854          trackCustomEvent(_this, "wpcf7_email_failed", eventData);
     855        },
     856        false
     857      );
     858    }
     859    if (
     860      wpGoalTrackerGa.formTrackingSettings.contactForm7Settings.trackInvalids
     861    ) {
     862      document.addEventListener(
     863        "wpcf7invalid",
     864        function (event) {
     865          var eventData = gtgaGetContactForm7EventData(event);
     866          trackCustomEvent(_this, "wpcf7_invalid", eventData);
     867        },
     868        false
     869      );
     870    }
     871    if (wpGoalTrackerGa.formTrackingSettings.contactForm7Settings.trackSpam) {
     872      document.addEventListener(
     873        "wpcf7spam",
     874        function (event) {
     875          var eventData = gtgaGetContactForm7EventData(event);
     876          trackCustomEvent(_this, "wpcf7_spam", eventData);
     877        },
     878        false
     879      );
     880    }
     881  }
     882  ////////////////////////////////////////////////////////////////
     883  /* </fs_premium_only> */
     884  function returnOriginalProp(self, prop) {
     885    return prop;
     886  }
     887  function getPageName() {
     888    if ("1" === wpGoalTrackerGa.isFrontPage) {
     889      return "Home";
     890    } else {
     891      if (typeof wpGoalTrackerGa.pageTitle !== "undefined") {
     892        return wpGoalTrackerGa.pageTitle;
     893      }
     894    }
     895    return "";
     896  }
     897  var trackCustomEvent =
     898    typeof trackCustomEventPro === "function"
     899      ? trackCustomEventPro
     900      : trackCustomEventBasic;
     901  var prepareProps =
     902    typeof get_placeholder === "function"
     903      ? get_placeholder
     904      : returnOriginalProp;
     905  return { isJustHashLink: isJustHashLink };
    277906})(jQuery);
    278 
     907/* <fs_premium_only> */
     908function getVideoPosition(currentPos, eventsSent) {
     909  var roundedPos = 0;
     910  if (currentPos > 10 && currentPos <= 24) {
     911    if (!eventsSent[10]) {
     912      roundedPos = 10;
     913    }
     914  } else if (currentPos >= 25 && currentPos <= 35) {
     915    if (!eventsSent[25]) {
     916      roundedPos = 25;
     917    }
     918  } else if (currentPos >= 50 && currentPos <= 60) {
     919    if (!eventsSent[50]) {
     920      roundedPos = 50;
     921    }
     922  } else if (currentPos >= 75 && currentPos <= 85) {
     923    if (!eventsSent[75]) {
     924      roundedPos = 75;
     925    }
     926  }
     927  return roundedPos;
     928}
     929function gtgaGetContactForm7EventData(event) {
     930  var eventTarget = event.target;
     931  var formTitle = jQuery("#" + eventTarget["wpcf7"].unitTag + " form").attr(
     932    "aria-label"
     933  );
     934  var eventData = {
     935    form_id: event.detail.contactFormId,
     936  };
     937  if (typeof formTitle !== "undefined") eventData["form_name"] = formTitle;
     938  return eventData;
     939}
     940function gtgaContactForm7Enabled() {
     941  return (
     942    typeof wpGoalTrackerGa.formTrackingSettings !== "undefined" &&
     943    wpGoalTrackerGa.formTrackingSettings.contactForm7Settings &&
     944    (wpGoalTrackerGa.formTrackingSettings.contactForm7Settings
     945      .trackFormSubmit ||
     946      wpGoalTrackerGa.formTrackingSettings.contactForm7Settings.trackInvalids ||
     947      wpGoalTrackerGa.formTrackingSettings.contactForm7Settings.trackMailSent ||
     948      wpGoalTrackerGa.formTrackingSettings.contactForm7Settings
     949        .trackMailFailed ||
     950      wpGoalTrackerGa.formTrackingSettings.contactForm7Settings.trackSpam)
     951  );
     952}
     953/* </fs_premium_only> */
  • goal-tracker-ga/trunk/public/src/wp-goal-tracker-ga-public.ts

    r2991535 r3011805  
    110110        event.currentTarget.nodeName == 'A')
    111111    ) {
    112       handleLinks(this, event);
     112      if ($(event.target).parent().attr('role') !== 'tab') {
     113        handleLinks(this, event);
     114      }
    113115    }
    114116  }; // End of click event function
Note: See TracChangeset for help on using the changeset viewer.