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

Make tracking work with site verification #65

Merged
merged 1 commit into from
May 27, 2024
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
8 changes: 6 additions & 2 deletions src/lib/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@ type EventPayload = {
readonly p?: string;
};

type CallbackArgs = {
readonly status: number;
};

// eslint-disable-next-line functional/no-mixed-type
export type EventOptions = {
/**
* Callback called when the event is successfully sent.
*/
readonly callback?: () => void;
readonly callback?: (args: CallbackArgs) => void;
/**
* Properties to be bound to the event.
*/
Expand Down Expand Up @@ -76,7 +80,7 @@ export function sendEvent(
req.onreadystatechange = () => {
if (req.readyState !== 4) return;
if (options && options.callback) {
options.callback();
options.callback({ status: req.status });
}
};
}
16 changes: 16 additions & 0 deletions src/lib/tracker.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { EventOptions, sendEvent } from './request';

declare global {
// eslint-disable-next-line functional/prefer-type-literal
interface Window {
// eslint-disable-next-line functional/prefer-readonly-type
plausible: TrackEvent;
}
}

/**
* Options used when initializing the tracker.
*/
Expand Down Expand Up @@ -207,6 +215,7 @@ type EnableAutoOutboundTracking = (
*
* @param defaults - Default event parameters that will be applied to all requests.
*/

export default function Plausible(
defaults?: PlausibleInitOptions
): {
Expand All @@ -215,6 +224,11 @@ export default function Plausible(
readonly enableAutoPageviews: EnableAutoPageviews;
readonly enableAutoOutboundTracking: EnableAutoOutboundTracking;
} {
const modifyWindow = () => {
// eslint-disable-next-line functional/immutable-data
window.plausible = trackEvent;
};

const getConfig = (): Required<PlausibleOptions> => ({
hashMode: false,
trackLocalhost: false,
Expand All @@ -230,6 +244,8 @@ export default function Plausible(
sendEvent(eventName, { ...getConfig(), ...eventData }, options);
};

modifyWindow();

const trackPageview: TrackPageview = (eventData, options) => {
trackEvent('pageview', options, eventData);
};
Expand Down
Loading
Loading