@benshi.ai/js-sdk
Version:
Benshi SDK
120 lines (87 loc) • 2.97 kB
text/typescript
import isBrowser from "is-in-browser";
import {
listenApplicationClose,
listenApplicationVisibilityChange,
listenPageChanged,
listenPageScrolled
} from "../drivers/BsSystem";
import BsLog from "../modules/BsLog";
import Navigation from "../modules/Navigation";
import { AppAction, AppProperties, PageProperties } from "../modules/Navigation/typings";
let lastPageChangeTimestamp = null
let currentPageURL = ''
let currentTitle = ''
const logOpenAppEvent = () => {
lastPageChangeTimestamp = new Date()
currentPageURL = window.location.href
currentTitle = document.title
const perfEntries = performance.getEntriesByType("navigation");
const appProperties: AppProperties = {
action: AppAction.Open,
start_time: Math.round((typeof perfEntries[0] === 'undefined') ? 0 : perfEntries[0].duration)
}
Navigation.logAppEvent(appProperties)
}
const logBackgroundEvent = () => {
const appProperties: AppProperties = {
action: AppAction.Background,
start_time: 0
}
Navigation.logAppEvent(appProperties)
}
const logResumeEvent = () => {
const appProperties: AppProperties = {
action: AppAction.Resume,
start_time: 0
}
Navigation.logAppEvent(appProperties)
}
const logPageChangedEvent = (path, title) => {
const currentTimestamp = Date.now()
const duration = Math.round((currentTimestamp - lastPageChangeTimestamp) / 1000)
const properties: PageProperties = {
path,
title,
duration
}
lastPageChangeTimestamp = currentTimestamp
Navigation.logPageEvent(properties)
}
const logPageCompletedEvent = (path, title) => {
const properties: PageProperties = {
path,
title,
}
Navigation.logPageEvent(properties)
}
export const init = (bslog: BsLog) => {
if (!isBrowser) {
return
}
const PAGE_COMPLETED_SCROLL_THRESHOLD = 90
let lastCompletedPageTracked = ''
// This function is called just once, so
// it is a good point to log the open event
// Previous implementation relied this on
// navigator listeners, but I did not find
// a homogenous behaviour across browsers
logOpenAppEvent()
listenApplicationClose(() => {
// console.warn('application is about to close: ', document.visibilityState)
// bslog.flush()
})
listenApplicationVisibilityChange(logResumeEvent, logBackgroundEvent)
listenPageChanged((path, title) => {
lastCompletedPageTracked=''
logPageChangedEvent(currentPageURL, currentTitle)
currentPageURL = path
currentTitle = title
})
listenPageScrolled(PAGE_COMPLETED_SCROLL_THRESHOLD, (scrollPercent) => {
if (lastCompletedPageTracked !== document.location.href) {
console.warn('triggering 90% completed paged!')
}
lastCompletedPageTracked = document.location.href
})
}
export default init