Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions __tests__/api/webchat/messages_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,26 @@ describe('WebchatMessagesAPI', () => {

afterEach(() => {
jest.restoreAllMocks()
Hellotext.page = undefined
})

it('sends the page the message is sent from', async () => {
Hellotext.page = {
trackingData: {
page: { url: 'https://shop.example.test/products/shirt', title: 'Shirt', path: '/products/shirt', section: 'product_details' },
},
}
const formData = new FormData()
formData.append('message[body]', 'Hello')

await new WebchatMessagesAPI('webchat-id').create(formData)

const body = global.fetch.mock.calls[0][1].body
expect(body.get('message[body]')).toBe('Hello')
expect(body.get('message[page][url]')).toBe('https://shop.example.test/products/shirt')
expect(body.get('message[page][title]')).toBe('Shirt')
expect(body.get('message[page][path]')).toBe('/products/shirt')
expect(body.get('message[page][section]')).toBe('product_details')
})

it('requests catch-up messages after the supplied message id', async () => {
Expand Down
3 changes: 1 addition & 2 deletions __tests__/controllers/webchat_controller_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2322,12 +2322,11 @@ describe('WebchatController', () => {
jest.useRealTimers()
})

it('tracks the open with the widget, page and time', () => {
it('tracks the open with the widget and time on the tracked page', () => {
controller.onPopoverOpened()

expect(Hellotext.track).toHaveBeenCalledWith('webchat.opened', {
webchat_id: 'test-webchat-id',
url: window.location.href,
tracked_at: new Date(2026, 10, 3, 12).toISOString(),
})
})
Expand Down
6 changes: 3 additions & 3 deletions __tests__/hellotext_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ describe("when the class is initialized successfully", () => {
describe("when hello_session is present in the query params", () => {
beforeAll(() => {
const windowMock = {
location: { search: "?hello_session=session" },
location: { search: "?hello_session=session", href: "https://example.com/?hello_session=session" },
}

jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock)
Expand Down Expand Up @@ -839,7 +839,7 @@ describe("when the class is initialized successfully", () => {
const business_id = "xy76ks"

beforeAll(() => {
const windowMock = {location: { search: "" },}
const windowMock = {location: { search: "", href: "https://example.com/" },}
jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock)
})

Expand Down Expand Up @@ -979,7 +979,7 @@ describe("when the class is initialized successfully", () => {

beforeAll(() => {
const windowMock = {
location: { search: "?hello_session=test_session" },
location: { search: "?hello_session=test_session", href: "https://example.com/?hello_session=test_session" },
}

jest.spyOn(global, 'window', 'get').mockImplementation(() => windowMock)
Expand Down
51 changes: 51 additions & 0 deletions __tests__/models/page_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,57 @@ describe('Page', () => {
})
})

describe('section', () => {
it('keeps a known section for the page it was set on', () => {
const page = new Page()

page.section = 'product_details'

expect(page.section).toBe('product_details')
expect(page.trackingData.page.section).toBe('product_details')
})

it('clears a section the integrations do not report', () => {
const page = new Page()
page.section = 'product_details'

page.section = 'checkout'

expect(page.section).toBeNull()
expect(page.trackingData.page).not.toHaveProperty('section')
})

it('clears itself once the visitor navigates to another page', () => {
const page = new Page()
page.section = 'homepage'

window.location.href = 'https://example.com/collections/shirts'
window.location.pathname = '/collections/shirts'

expect(page.section).toBeNull()
})

it('clears itself when a hash route changes', () => {
window.location.href = 'https://example.com/#/products/shirt'
window.location.pathname = '/'
const page = new Page()
page.section = 'product_details'

window.location.href = 'https://example.com/#/checkout'

expect(page.section).toBeNull()
})

it('keeps the section on the same route with another query or anchor', () => {
const page = new Page()
page.section = 'product_details'

window.location.href = 'https://example.com/current-page?color=red#reviews'

expect(page.section).toBe('product_details')
})
})

describe('trackingData getter', () => {
it('returns complete tracking data with default values', () => {
mockUtm.current = { source: 'facebook', medium: 'social' }
Expand Down
2 changes: 1 addition & 1 deletion dist/hellotext.js

Large diffs are not rendered by default.

15 changes: 15 additions & 0 deletions docs/tracking.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,21 @@ Hellotext.track('page.viewed', {
})
```

#### Page Section

Store integrations know which kind of page the visitor is on. After initializing the SDK, set it once
per page and every tracked event, Webchat messages included, reports it with the page:

```javascript
Hellotext.page.section = 'product_details'
// On the homepage: 'homepage'
// On a collection page: 'product_collection'
```

Any other value clears it. The section belongs to the page it was set on (its path, plus its hash route
on hash-routed sites), so it clears itself when the visitor navigates to another page, and an event
tracked with its own `url` has none.

### Headers

You can add any custom or additional headers to the request by passing a `headers` object in the parameter.
Expand Down
10 changes: 10 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ export interface HellotextPush {

export type HellotextAlertSection = 'homepage' | 'product_collection' | 'product_details'

export type HellotextPageSection = HellotextAlertSection

export interface HellotextPage {
readonly url: string
readonly title: string
readonly path: string
section: HellotextPageSection | null
}

export interface HellotextAlertShowOptions {
force?: boolean
title?: string
Expand Down Expand Up @@ -191,6 +200,7 @@ declare class Hellotext {
static whatsapp: any
static push: HellotextPush | null
static alert: HellotextAlert | null
static page: HellotextPage
}

export declare class User {
Expand Down
10 changes: 10 additions & 0 deletions lib/api/webchat/messages.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class WebchatMessagesAPI {
});
}
async create(formData) {
this.appendPage(formData);
const response = await fetch(this.url, {
method: 'POST',
headers: {
Expand All @@ -54,6 +55,15 @@ class WebchatMessagesAPI {
get url() {
return WebchatMessagesAPI.endpoint.replace(':id', this.webchatId);
}

// The page the message is sent from, as every tracked event reports it, so the
// conversation it starts is counted on that page.
appendPage(formData) {
const page = _hellotext.default.page?.trackingData?.page || {};
Object.entries(page).forEach(([key, value]) => {
if (value) formData.append(`message[page][${key}]`, value);
});
}
}
var _default = WebchatMessagesAPI;
exports.default = _default;
10 changes: 10 additions & 0 deletions lib/api/webchat/messages.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class WebchatMessagesAPI {
});
}
async create(formData) {
this.appendPage(formData);
const response = await fetch(this.url, {
method: 'POST',
headers: {
Expand All @@ -47,5 +48,14 @@ class WebchatMessagesAPI {
get url() {
return WebchatMessagesAPI.endpoint.replace(':id', this.webchatId);
}

// The page the message is sent from, as every tracked event reports it, so the
// conversation it starts is counted on that page.
appendPage(formData) {
const page = Hellotext.page?.trackingData?.page || {};
Object.entries(page).forEach(([key, value]) => {
if (value) formData.append(`message[page][${key}]`, value);
});
}
}
export default WebchatMessagesAPI;
4 changes: 2 additions & 2 deletions lib/controllers/webchat_controller.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -367,15 +367,15 @@ class _default extends _stimulus.Controller {
}

// Reports the open once per session and day, which is how the Webchat report
// counts openers. A failed report is sent again on the next open.
// counts openers. A failed report is sent again on the next open. The page,
// with its section, is the one every tracked event carries.
async trackOpen() {
const key = `hellotext--webchat--${this.idValue}--tracked-open`;
const marker = `${_hellotext.default.session}:${this.localDate}`;
if (_hellotext.default.readStorage('localStorage', key) === marker) return;
try {
const response = await _hellotext.default.track('webchat.opened', {
webchat_id: this.idValue,
url: window.location.href,
tracked_at: new Date().toISOString()
});
if (response?.succeeded) _hellotext.default.writeStorage('localStorage', key, marker);
Expand Down
4 changes: 2 additions & 2 deletions lib/controllers/webchat_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -360,15 +360,15 @@ export default class extends Controller {
}

// Reports the open once per session and day, which is how the Webchat report
// counts openers. A failed report is sent again on the next open.
// counts openers. A failed report is sent again on the next open. The page,
// with its section, is the one every tracked event carries.
async trackOpen() {
const key = `hellotext--webchat--${this.idValue}--tracked-open`;
const marker = `${Hellotext.session}:${this.localDate}`;
if (Hellotext.readStorage('localStorage', key) === marker) return;
try {
const response = await Hellotext.track('webchat.opened', {
webchat_id: this.idValue,
url: window.location.href,
tracked_at: new Date().toISOString()
});
if (response?.succeeded) Hellotext.writeStorage('localStorage', key, marker);
Expand Down
5 changes: 1 addition & 4 deletions lib/hellotext.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -311,10 +311,7 @@ class Hellotext {
return window.performance?.timeOrigin || Date.now();
}
static pageRoute(value = window.location.href) {
const currentUrl = window.location?.href || document.location?.href || 'http://localhost/';
const url = new URL(value || currentUrl, currentUrl);
const hashRoute = url.hash.match(/^#!?\/[^?]*/)?.[0];
return `${url.pathname}${hashRoute?.replace(/^#!/, '#') || ''}`;
return _models.Page.route(value);
}
static readStoredActivities() {
try {
Expand Down
5 changes: 1 addition & 4 deletions lib/hellotext.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,10 +304,7 @@ class Hellotext {
return window.performance?.timeOrigin || Date.now();
}
static pageRoute(value = window.location.href) {
const currentUrl = window.location?.href || document.location?.href || 'http://localhost/';
const url = new URL(value || currentUrl, currentUrl);
const hashRoute = url.hash.match(/^#!?\/[^?]*/)?.[0];
return `${url.pathname}${hashRoute?.replace(/^#!/, '#') || ''}`;
return Page.route(value);
}
static readStoredActivities() {
try {
Expand Down
45 changes: 42 additions & 3 deletions lib/models/page.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,44 @@ Object.defineProperty(exports, "__esModule", {
});
exports.Page = void 0;
var _utm = require("./utm");
const SECTIONS = ['homepage', 'product_collection', 'product_details'];
class Page {
/**
* The route a URL is on: its path, plus its hash route (`#/…` or `#!/…`) on hash-routed
* sites. A query string or a plain anchor stays on the same route.
* @param {string} value - The URL, the current one by default
* @returns {string} The route
*/
static route(value = window.location.href) {
const url = new URL(value || window.location.href, window.location.href);
const hashRoute = url.hash.match(/^#!?\/[^?]*/)?.[0];
return `${url.pathname}${hashRoute?.replace(/^#!/, '#') || ''}`;
}
constructor(url = null) {
this.utm = new _utm.UTM();
this._url = url;
this._section = null;
}

/**
* The kind of page this is, as the store's integration reports it. It belongs to the
* route it was set on, so it clears itself once the visitor navigates to another page.
* @returns {('homepage'|'product_collection'|'product_details'|null)} The page section
*/
get section() {
if (!this._section || this._section.route !== Page.route(this.url)) return null;
return this._section.value;
}

/**
* Sets the page section. Anything other than a known section clears it.
* @param {('homepage'|'product_collection'|'product_details'|null)} value - The page section
*/
set section(value) {
this._section = SECTIONS.includes(value) ? {
value,
route: Page.route(this.url)
} : null;
}

/**
Expand Down Expand Up @@ -52,16 +86,21 @@ class Page {

/**
* Get page data for tracking
* @returns {Object} Object containing page object, utm_params and, when the
* visitor clicked one of the site's own UTM links, internal_utm_params
* @returns {Object} Object containing page object (with its section, when one is set),
* utm_params and, when the visitor clicked one of the site's own UTM links,
* internal_utm_params
*/
get trackingData() {
const internalUtmParams = this.utm.internal || {};
const section = this.section;
return {
page: {
url: this.url,
title: this.title,
path: this.path
path: this.path,
...(section && {
section
})
},
utm_params: this.utmParams,
...(Object.keys(internalUtmParams).length && {
Expand Down
Loading
Loading