All files referrer.js

83.33% Statements 10/12
83.33% Branches 5/6
75% Functions 3/4
83.33% Lines 10/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 36 37 38 39 40 41 42 43 44 45 463x               3x       25x                           3x 51x     51x       51x           3x 10x   10x    
export const referrerState = {
  spaReferrer: '',
  referrer: ''
}
 
/**
 * Useful wrapper around document and window objects
 */
export const utils = {
  /**
   * @returns {string} The referrer of the document
   */
  getDocumentReferrer: () => document.referrer,
  /**
   * @returns {string} The actual location with protocol, domain and pathname
   */
  getActualLocation: () => {
    const {origin, pathname} = window.location
    return `${origin}${pathname}`
  }
}
 
/**
 * Get the correct page referrer for SPA navigations
 * @returns {string}  referrer
 */
export const getPageReferrer = ({isPageTrack = false} = {}) => {
  const {referrer, spaReferrer} = referrerState
  // if we're a page, we should use the new referrer that was calculated with the previous location
  // if we're a track, we should use the previous referrer, as the location hasn't changed yet
  const referrerToUse = isPageTrack ? referrer : spaReferrer
  // as a fallback for page and tracks, we must use always the document.referrer
  // because some sites could not be using `page` or a `track` could be done
  // even before the first page
  return referrerToUse || utils.getDocumentReferrer()
}
 
/**
 * Update page referrer for SPA navigations
 */
export const updatePageReferrer = () => {
  referrerState.spaReferrer = getPageReferrer({isPageTrack: true})
  // mutate actualReferrer with what will be the new referrer
  referrerState.referrer = utils.getActualLocation()
}