Advertisement
VKirill

60sec - Yandex Metrika - Script

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