VKirill

56660560

Nov 17th, 2022
613
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script>
  2. var settings = {
  3.     /* Настройки которые надо менять */
  4.     need: 30, // Сюда вписываем через какое количество секунд повторно отправлять цель, по умолчанию стоит 60, но можно указать и 30
  5.     checkTime: 10, // секунды. период проверки.
  6.     //желательно, чтобы need было кратно checkTime
  7.     IDmetrika: 56660560, // Сюда вписываем ИД Счетчика Яндекс Метрики
  8.     /* Настройки которые надо менять */
  9. }
  10.  
  11. /*
  12. ## Инструкция по добавлению целей в Яндекс.Метрику ##
  13. Если вы указываете в функции NEED шаг в 30 секунд, то в Метрике вы можете отслеживать цели с шагом в 30 секунд и цели событий добавляйте такие:
  14. 30sec
  15. 60sec
  16. 90sec
  17. 120sec
  18. 150sec и т.д.
  19.  
  20. Если вы указываете в функции NEED шаг в 60 секунд, то в Метрике вы можете отслеживать цели с шагом в 30 секунд и цели событий добавляйте такие:
  21. 60sec
  22. 120sec
  23. 180sec
  24. 240sec и т.д.
  25. */
  26.  
  27. /* БОЛЬШЕ В КОДЕ НИЧЕГО НЕ ТРОГАЕМ, ЦЕЛИ ТОЖЕ НЕ ПРАВИМ */
  28. function gtag(){dataLayer.push(arguments);}
  29.  
  30. var metricsFn = function () {
  31.     console.log(ActiveScore.timer);
  32.     console.log(ActiveScore.need);
  33.     var c1 = this.getCookie(this.cookieName);
  34.     console.log(c1);
  35.     if (ActiveScore.timer >= ActiveScore.need) {
  36.         console.log("событие отправилось");
  37.         /* Тут перечислять все что нужно будет вызвать по достижению цели */
  38.         ym(settings.IDmetrika, "reachGoal", this.cookieName.slice(0, -3));
  39.    
  40.        
  41.         /* Тут перечислять все что нужно будет вызвать по достижению цели */
  42.     }
  43. };
  44.  
  45. var ActiveScore = {
  46.     need: settings.need,
  47.     checkTime: settings.checkTime,
  48.     loop: true,
  49.     counter: 0,
  50.     cookieName: "60sec_ap",
  51.     sendFn: null,
  52.     parts: 0,
  53.     active_parts: 0,
  54.     timer: 0,
  55.     events: [
  56.         "touchmove",
  57.         "blur",
  58.         "focus",
  59.         "focusin",
  60.         "focusout",
  61.         "load",
  62.         "resize",
  63.         "scroll",
  64.         "unload",
  65.         "click",
  66.         "dblclick",
  67.         "mousedown",
  68.         "mouseup",
  69.         "mousemove",
  70.         "mouseover",
  71.         "mouseout",
  72.         "mouseenter",
  73.         "mouseleave",
  74.         "change",
  75.         "select",
  76.         "submit",
  77.         "keydown",
  78.         "keypress",
  79.         "keyup",
  80.         "error",
  81.     ],
  82.  
  83.     setEvents: function () {
  84.         for (var index = 0; index < this.events.length; index++) {
  85.             var eName = this.events[index];
  86.             window.addEventListener(eName, function (e) {
  87.                 if (e.isTrusted && ActiveScore.period.events == false) {
  88.                     ActiveScore.period.events = true;
  89.                 }
  90.             });
  91.         }
  92.     },
  93.  
  94.     period: {
  95.         start: 0,
  96.         end: 0,
  97.         events: false,
  98.     },
  99.  
  100.     init: function (fn) {
  101.         this.calcParts();
  102.         this.setEvents();
  103.         this.setStartCounter();
  104.         if (this.checkCookie()) {
  105.             this.sendFn = fn;
  106.             this.start();
  107.         }
  108.     },
  109.  
  110.     readLastCookie: function () {
  111.         var absurdlyLarge = 100000;
  112.         for (var i = 1; i < absurdlyLarge; i++) {
  113.             var cookie = this.getCookie(i * this.need + 'sec_ap');
  114.             if (cookie != this.parts * this.parts) return { i: i, cookie: cookie };
  115.         }
  116.         return { i: 1, cookie: 0 };
  117.     },
  118.  
  119.     setStartCounter: function () {
  120.         var lastCookie = this.readLastCookie();
  121.         this.counter = lastCookie.i - 1;
  122.         this.active_parts = Number(lastCookie.cookie);
  123.         this.cookieName = (this.counter + 1) * this.need + "sec_ap";
  124.     },
  125.  
  126.     calcParts: function () {
  127.         this.parts = Math.ceil(this.need / this.checkTime);
  128.     },
  129.  
  130.     setPeriod: function () {
  131.         this.period.start = this.microtime();
  132.         this.period.end = this.period.start + this.checkTime;
  133.         this.period.events = false;
  134.     },
  135.  
  136.     microtime: function () {
  137.         var now = new Date().getTime() / 1000;
  138.         var s = parseInt(now);
  139.         return s;
  140.     },
  141.  
  142.     start: function () {
  143.         this.setPeriod();
  144.         this.runPeriod();
  145.     },
  146.  
  147.     timeoutId: null,
  148.  
  149.     checkPeriod: function () {
  150.         if (this.period.events == true) {
  151.             this.active_parts = this.active_parts + 1;
  152.             // console.log('В этой секции были действия');
  153.         } else {
  154.             // console.log('В этой секции НЕБЫЛО действия');
  155.         }
  156.         this.timer = this.active_parts * this.checkTime;
  157.         console.log(
  158.             this.active_parts + " / " + this.parts + " [" + this.timer + "]"
  159.         );
  160.  
  161.         if (this.checkSecs()) {
  162.         } else {
  163.             this.start();
  164.         }
  165.         this.setCookie(this.cookieName, this.active_parts);
  166.     },
  167.  
  168.     checkSecs: function () {
  169.         if (this.timer >= this.need) {
  170.             this.send();
  171.             if (this.loop == true) {
  172.                 this.counter++;
  173.                 this.timer = 0;
  174.                 this.active_parts = 0;
  175.                 this.cookieName = (this.counter + 1) * this.need + "sec_ap";
  176.                 return false;
  177.             } else {
  178.                 // console.log('Завершили проверку активности');
  179.                 return true;
  180.             }
  181.         }
  182.         return false;
  183.     },
  184.  
  185.     timeoutFn: function () {
  186.         ActiveScore.checkPeriod();
  187.     },
  188.  
  189.     runPeriod: function () {
  190.         this.timeoutId = setTimeout(this.timeoutFn, this.checkTime * 1000);
  191.     },
  192.  
  193.     send: function () {
  194.         if (this.getCookie(this.cookieName) == this.parts * this.parts) {
  195.             this.setStartCounter();
  196.         } else {
  197.             this.setCookie(this.cookieName, this.active_parts * this.active_parts);
  198.         }
  199.         this.sendFn();
  200.     },
  201.  
  202.     checkCookie: function () {
  203.         var c = this.getCookie(this.cookieName);
  204.         if (c == null) {
  205.             return true;
  206.         } else {
  207.             if (c == '') return true;
  208.             c = parseInt(c);
  209.             if (c >= this.parts) {
  210.                 // console.log('Скрипт даже не запустился...');
  211.                 if (this.loop == true) {
  212.                     return true;
  213.                 }
  214.                 return false;
  215.             } else {
  216.                 this.active_parts = c;
  217.                 return true;
  218.             }
  219.         }
  220.     },
  221.  
  222.     setCookie: function (name, value, days) {
  223.         var expires = "";
  224.         if (days) {
  225.             var date = new Date();
  226.             date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  227.             expires = "; expires=" + date.toUTCString();
  228.         }
  229.         document.cookie = name + "=" + (value || "") + expires + "; path=/";
  230.     },
  231.     getCookie: function (name) {
  232.         var nameEQ = name + "=";
  233.         var ca = document.cookie.split(";");
  234.         for (var i = 0; i < ca.length; i++) {
  235.             var c = ca[i];
  236.             while (c.charAt(0) == " ") c = c.substring(1, c.length);
  237.             if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
  238.         }
  239.         return null;
  240.     },
  241.     eraseCookie: function (name) {
  242.         document.cookie =
  243.             name + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
  244.     },
  245. };
  246.  
  247. ActiveScore.init(metricsFn);
  248. </script>
Advertisement
Add Comment
Please, Sign In to add comment