1+ interface AnalyticsModel {
2+ run : typeof run
3+ }
4+
5+ var Analytics :AnalyticsModel = {
6+ run : run
7+ } ;
8+
9+ function run ( ) :any {
10+ let hostName :string = window . location . hostname ;
11+ let interval :number ;
12+ let frequency :number = 200 ;
13+
14+ // set up interval and send api call on initialization
15+ setAnalyticInterval ( ) ;
16+ sendApiRequest ( ) ;
17+
18+ document . addEventListener ( "visibilitychange" , onVisibleChange ) ;
19+
20+ function setAnalyticInterval ( ) :any {
21+ let prevLocation :string = window . location . href ;
22+ let presentLocation :string = window . location . href ;
23+ interval = setInterval ( ( ) => {
24+ presentLocation = window . location . href ;
25+
26+ if ( prevLocation === presentLocation ) {
27+ return ;
28+ }
29+
30+ // call api and set prevLocation to presentLocation
31+ sendApiRequest ( ) ;
32+ prevLocation = presentLocation ;
33+ } , frequency )
34+ }
35+
36+ function sendApiRequest ( ) :any {
37+
38+ let body = {
39+ AppId : hostName ,
40+ PageName : '' ,
41+ Enter : false
42+ } ;
43+
44+ let pathName : string = window . location . pathname ;
45+ let pathArray : string [ ] = pathName . split ( '/' ) ;
46+ let pageName : string = pathArray [ 1 ] ;
47+ if ( pageName && ( pageName . length > 0 ) ) {
48+ body = {
49+ AppId : hostName ,
50+ PageName : pageName ,
51+ Enter : true
52+ } ;
53+ }
54+
55+ fetch ( 'https://saffroncodesdk.com/api/Projects/versioncontrol' , {
56+ method : 'POST' ,
57+ body : JSON . stringify ( body ) ,
58+ } )
59+ . then ( response => response . json ( ) )
60+ . then ( data => console . log ( data ) ) ;
61+ }
62+
63+ function onVisibleChange ( ) {
64+ // if page is hidden to user (minimize or on another tab)
65+ // clear interval and set interval again if page is visible
66+ // to user and also send api request
67+
68+ let isHidden :boolean = document . hidden ;
69+ if ( isHidden ) {
70+ clearInterval ( interval ) ;
71+ return ;
72+ }
73+ clearInterval ( interval ) ;
74+ setAnalyticInterval ( ) ;
75+ sendApiRequest ( ) ;
76+
77+ // console.log(document.hidden, 'isHidden', document.visibilityState, 'state');
78+ }
79+ }
80+
81+ export default Analytics ;
0 commit comments