summaryrefslogtreecommitdiff
blob: 0273932ca04e16cd22280750436c00d960b92c84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * External dependencies
 */
import cookie from 'cookie';

/**
 * Internal dependencies
 */
import { COOKIE_NAME, MAX_COOKIE_AGE } from './constants';

function getViewCount() {
	const cookies = cookie.parse( document.cookie );
	const value = cookies[ COOKIE_NAME ] || 0;
	return +value;
}

function setViewCount( value ) {
	document.cookie = cookie.serialize( COOKIE_NAME, value, {
		path: window.location.pathname,
		maxAge: MAX_COOKIE_AGE,
	} );
}

function incrementCookieValue() {
	const repeatVisitorBlocks = Array.from(
		document.querySelectorAll( '.wp-block-jetpack-repeat-visitor' )
	);
	if ( repeatVisitorBlocks.length === 0 ) {
		return;
	}

	setViewCount( getViewCount() + 1 );
}

window && window.addEventListener( 'load', incrementCookieValue );