Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Honor target attribute for outbound link tracking by relying on navigator.sendBeacon #54

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ const plausible = Plausible({
| hashMode | `bool` | Enables tracking based on URL hash changes. | `false` |
| trackLocalhost | `bool` | Enables tracking on *localhost*. | `false` |
| apiHost | `string` | Plausible's API host to use. Change this if you are self-hosting. | `'https://plausible.io'` |
| useSendBeacon | `bool` | Enables the use of `navigator.sendBeacon` method to send events. | `false` |

The object returned from `Plausible()` contains the functions that you'll use to track your events. These functions are:

Expand Down Expand Up @@ -207,7 +208,7 @@ You can also track all clicks to outbound links using `enableAutoOutboundTrackin

For details on how to setup the tracking, visit the [docs](https://docs.plausible.io/outbound-link-click-tracking).

This function adds a `click` event listener to all `a` tags on the page and reports them to Plausible. It also creates a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) that efficiently tracks node mutations, so dynamically-added links are also tracked.
This function adds a `click` event listener to all `a` tags on the page and reports them to Plausible. It also creates a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) that efficiently tracks node mutations, so dynamically-added links are also tracked. Event is sent with `navigator.sendBeacon` method.

```ts
import Plausible from 'plausible-tracker'
Expand Down
27 changes: 27 additions & 0 deletions src/lib/request.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,17 @@ let xhrMockClass: ReturnType<typeof getXhrMockClass>;

const xmr = jest.spyOn(window, 'XMLHttpRequest');

Object.assign(navigator, {
sendBeacon() {
// just making node aware this function exists
},
});
const sendBeacon = jest.spyOn(navigator, 'sendBeacon');

const defaultData: Required<PlausibleOptions> = {
hashMode: false,
trackLocalhost: false,
useSendBeacon: false,
url: 'https://my-app.com/my-url',
domain: 'my-app.com',
referrer: null,
Expand Down Expand Up @@ -78,6 +86,25 @@ describe('sendEvent', () => {

expect(xhrMockClass.send).toHaveBeenCalledWith(JSON.stringify(payload));
});
test('sends via Navigator#sendBeacon', () => {
expect(sendBeacon).not.toHaveBeenCalled();
sendEvent('myEvent', { ...defaultData, useSendBeacon: true });
expect(sendBeacon).toHaveBeenCalledTimes(1);

const payload = {
n: 'myEvent',
u: defaultData.url,
d: defaultData.domain,
r: defaultData.referrer,
w: defaultData.deviceWidth,
h: 0,
};

expect(sendBeacon).toHaveBeenCalledWith(
`${defaultData.apiHost}/api/event`,
JSON.stringify(payload)
);
});
test('hash mode', () => {
expect(xmr).not.toHaveBeenCalled();
sendEvent('myEvent', { ...defaultData, hashMode: true });
Expand Down
28 changes: 16 additions & 12 deletions src/lib/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ type EventPayload = {
readonly p?: string;
};

// eslint-disable-next-line functional/no-mixed-type
export type EventOptions = {
/**
* Callback called when the event is successfully sent.
* Does not work with `useSendBeacon = true`.
*/
readonly callback?: () => void;
/**
Expand Down Expand Up @@ -68,15 +68,19 @@ export function sendEvent(
p: options && options.props ? JSON.stringify(options.props) : undefined,
};

const req = new XMLHttpRequest();
req.open('POST', `${data.apiHost}/api/event`, true);
req.setRequestHeader('Content-Type', 'text/plain');
req.send(JSON.stringify(payload));
// eslint-disable-next-line functional/immutable-data
req.onreadystatechange = () => {
if (req.readyState !== 4) return;
if (options && options.callback) {
options.callback();
}
};
if (!data?.useSendBeacon) {
const req = new XMLHttpRequest();
req.open('POST', `${data.apiHost}/api/event`, true);
req.setRequestHeader('Content-Type', 'text/plain');
req.send(JSON.stringify(payload));
// eslint-disable-next-line functional/immutable-data
req.onreadystatechange = () => {
if (req.readyState !== 4) return;
if (options && options.callback) {
options.callback();
}
};
} else {
navigator.sendBeacon(`${data.apiHost}/api/event`, JSON.stringify(payload));
}
}
2 changes: 2 additions & 0 deletions src/lib/tracker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ describe('tracker', () => {
const getDefaultData: () => Required<PlausibleOptions> = () => ({
hashMode: false,
trackLocalhost: false,
useSendBeacon: false,
url: location.href,
domain: location.hostname,
referrer: document.referrer || null,
Expand All @@ -23,6 +24,7 @@ describe('tracker', () => {
const getCustomData: () => Required<PlausibleOptions> = () => ({
hashMode: true,
trackLocalhost: true,
useSendBeacon: false,
url: 'https://my-url.com',
domain: 'my-domain.com',
referrer: 'my-referrer',
Expand Down
28 changes: 8 additions & 20 deletions src/lib/tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ export type PlausibleInitOptions = {
* Defaults to `'https://plausible.io'`
*/
readonly apiHost?: string;
/**
* Whether to use `Navigator#sendBeacon`.
* Defaults to `false`.
*/
readonly useSendBeacon?: boolean;
};

/**
Expand Down Expand Up @@ -223,6 +228,7 @@ export default function Plausible(
referrer: document.referrer || null,
deviceWidth: window.innerWidth,
apiHost: 'https://plausible.io',
useSendBeacon: false,
...defaults,
});

Expand Down Expand Up @@ -276,26 +282,8 @@ export default function Plausible(
attributeFilter: ['href'],
}
) => {
function trackClick(this: HTMLAnchorElement, event: MouseEvent) {
trackEvent('Outbound Link: Click', { props: { url: this.href } });

/* istanbul ignore next */
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (
!(
typeof process !== 'undefined' &&
process &&
process.env.NODE_ENV === 'test'
)
) {
setTimeout(() => {
// eslint-disable-next-line functional/immutable-data
location.href = this.href;
}, 150);
}

event.preventDefault();
function trackClick(this: HTMLAnchorElement, _: MouseEvent) {
trackEvent('Outbound Link: Click', { props: { url: this.href } }, { useSendBeacon: true });
}

// eslint-disable-next-line functional/prefer-readonly-type
Expand Down