View difference between Paste ID: JGJLEuyq and hnziJ2vi
SHOW: | | - or go back to the newest paste.
1
<script>
2
var settings = {
3
    /* Настройки которые надо менять */
4
    need: 30, // Сюда вписываем через какое количество секунд повторно отправлять цель, по умолчанию стоит 60, но можно указать и 30
5
    checkTime: 10, // секунды. период проверки. 
6
    //желательно, чтобы need было кратно checkTime
7-
	IDmetrika: 92093006, // Сюда вписываем ИД Счетчика Яндекс Метрики
7+
	IDmetrika: 91576698, // Сюда вписываем ИД Счетчика Яндекс Метрики
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
var ActiveScore = {
45
    need: settings.need,
46
    checkTime: settings.checkTime,
47
    loop: true,
48
    counter: 0,
49
    cookieName: "60sec_ap",
50
    sendFn: null,
51
    parts: 0,
52
    active_parts: 0,
53
    timer: 0,
54
    events: [
55
        "touchmove",
56
        "blur",
57
        "focus",
58
        "focusin",
59
        "focusout",
60
        "load",
61
        "resize",
62
        "scroll",
63
        "unload",
64
        "click",
65
        "dblclick",
66
        "mousedown",
67
        "mouseup",
68
        "mousemove",
69
        "mouseover",
70
        "mouseout",
71
        "mouseenter",
72
        "mouseleave",
73
        "change",
74
        "select",
75
        "submit",
76
        "keydown",
77
        "keypress",
78
        "keyup",
79
        "error",
80
    ],
81
82
    setEvents: function () {
83
        for (var index = 0; index < this.events.length; index++) {
84
            var eName = this.events[index];
85
            window.addEventListener(eName, function (e) {
86
                if (e.isTrusted && ActiveScore.period.events == false) {
87
                    ActiveScore.period.events = true;
88
                }
89
            });
90
        }
91
    },
92
93
    period: {
94
        start: 0,
95
        end: 0,
96
        events: false,
97
    },
98
99
    init: function (fn) {
100
        this.calcParts();
101
        this.setEvents();
102
        this.setStartCounter();
103
        if (this.checkCookie()) {
104
            this.sendFn = fn;
105
            this.start();
106
        }
107
    },
108
109
    readLastCookie: function () {
110
        var absurdlyLarge = 100000;
111
        for (var i = 1; i < absurdlyLarge; i++) {
112
            var cookie = this.getCookie(i * this.need + 'sec_ap');
113
            if (cookie != this.parts * this.parts) return { i: i, cookie: cookie };
114
        }
115
        return { i: 1, cookie: 0 };
116
    },
117
118
    setStartCounter: function () {
119
        var lastCookie = this.readLastCookie();
120
        this.counter = lastCookie.i - 1;
121
        this.active_parts = Number(lastCookie.cookie);
122
        this.cookieName = (this.counter + 1) * this.need + "sec_ap";
123
    },
124
125
    calcParts: function () {
126
        this.parts = Math.ceil(this.need / this.checkTime);
127
    },
128
129
    setPeriod: function () {
130
        this.period.start = this.microtime();
131
        this.period.end = this.period.start + this.checkTime;
132
        this.period.events = false;
133
    },
134
135
    microtime: function () {
136
        var now = new Date().getTime() / 1000;
137
        var s = parseInt(now);
138
        return s;
139
    },
140
141
    start: function () {
142
        this.setPeriod();
143
        this.runPeriod();
144
    },
145
146
    timeoutId: null,
147
148
    checkPeriod: function () {
149
        if (this.period.events == true) {
150
            this.active_parts = this.active_parts + 1;
151
            // console.log('В этой секции были действия');
152
        } else {
153
            // console.log('В этой секции НЕБЫЛО действия');
154
        }
155
        this.timer = this.active_parts * this.checkTime;
156
        console.log(
157
            this.active_parts + " / " + this.parts + " [" + this.timer + "]"
158
        );
159
160
        if (this.checkSecs()) {
161
        } else {
162
            this.start();
163
        }
164
        this.setCookie(this.cookieName, this.active_parts);
165
    },
166
167
    checkSecs: function () {
168
        if (this.timer >= this.need) {
169
            this.send();
170
            if (this.loop == true) {
171
                this.counter++;
172
                this.timer = 0;
173
                this.active_parts = 0;
174
                this.cookieName = (this.counter + 1) * this.need + "sec_ap";
175
                return false;
176
            } else {
177
                // console.log('Завершили проверку активности');
178
                return true;
179
            }
180
        }
181
        return false;
182
    },
183
184
    timeoutFn: function () {
185
        ActiveScore.checkPeriod();
186
    },
187
188
    runPeriod: function () {
189
        this.timeoutId = setTimeout(this.timeoutFn, this.checkTime * 1000);
190
    },
191
192
    send: function () {
193
        if (this.getCookie(this.cookieName) == this.parts * this.parts) {
194
            this.setStartCounter();
195
        } else {
196
            this.setCookie(this.cookieName, this.active_parts * this.active_parts);
197
        }
198
        this.sendFn();
199
    },
200
201
    checkCookie: function () {
202
        var c = this.getCookie(this.cookieName);
203
        if (c == null) {
204
            return true;
205
        } else {
206
            if (c == '') return true;
207
            c = parseInt(c);
208
            if (c >= this.parts) {
209
                // console.log('Скрипт даже не запустился...');
210
                if (this.loop == true) {
211
                    return true;
212
                }
213
                return false;
214
            } else {
215
                this.active_parts = c;
216
                return true;
217
            }
218
        }
219
    },
220
221
    setCookie: function (name, value, days) {
222
        var expires = "";
223
        if (days) {
224
            var date = new Date();
225
            date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
226
            expires = "; expires=" + date.toUTCString();
227
        }
228
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
229
    },
230
    getCookie: function (name) {
231
        var nameEQ = name + "=";
232
        var ca = document.cookie.split(";");
233
        for (var i = 0; i < ca.length; i++) {
234
            var c = ca[i];
235
            while (c.charAt(0) == " ") c = c.substring(1, c.length);
236
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
237
        }
238
        return null;
239
    },
240
    eraseCookie: function (name) {
241
        document.cookie =
242
            name + "=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
243
    },
244
};
245
246
ActiveScore.init(metricsFn);
247
</script>