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