Skip to content

Commit

Permalink
Fix multiple link click events tracked for a single tracker in case m…
Browse files Browse the repository at this point in the history
…ultiple trackers are initialized on the page (close #1384)
  • Loading branch information
matus-tomlein committed Nov 20, 2024
1 parent c4a1b2a commit ccf828c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 9 deletions.
22 changes: 14 additions & 8 deletions plugins/browser-plugin-link-click-tracking/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,10 +274,13 @@ function clickHandler(tracker: string, evt: MouseEvent | undefined): void {

// Using evt.type (added in IE4), we avoid defining separate handlers for mouseup and mousedown.
if (event.type === 'click') {
trackLinkClick({
element: target,
context: resolveDynamicContext(context, target),
});
trackLinkClick(
{
element: target,
context: resolveDynamicContext(context, target),
},
[tracker]
);
} else if (event.type === 'mousedown') {
if (button === 1 || button === 2) {
_configuration[tracker].lastButton = button;
Expand All @@ -287,10 +290,13 @@ function clickHandler(tracker: string, evt: MouseEvent | undefined): void {
}
} else if (event.type === 'mouseup') {
if (button === _configuration[tracker].lastButton && target === _configuration[tracker].lastTarget) {
trackLinkClick({
element: target,
context: resolveDynamicContext(context, target),
});
trackLinkClick(
{
element: target,
context: resolveDynamicContext(context, target),
},
[tracker]
);
}
delete _configuration[tracker].lastButton;
delete _configuration[tracker].lastTarget;
Expand Down
22 changes: 21 additions & 1 deletion plugins/browser-plugin-link-click-tracking/test/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,26 @@ describe('LinkClickTrackingPlugin', () => {

expect(await eventStore.getAllPayloads()).toHaveLength(1);
});

it('tracks a single link click with each tracker', async () => {
addTracker('sp2', 'sp2', 'js-3.0.0', '', new SharedState(), {
stateStorageStrategy: 'cookie',
encodeBase64: false,
plugins: [LinkClickTrackingPlugin()],
eventStore,
customFetch: async () => new Response(null, { status: 500 }),
});

enableLinkClickTracking();

const target = document.createElement('a');
target.href = 'https://www.example.com/exists';
document.body.appendChild(target);

target.click();

expect(await eventStore.getAllPayloads()).toHaveLength(2);
});
});

describe('disableLinkClickTracking', () => {
Expand All @@ -351,7 +371,7 @@ describe('LinkClickTrackingPlugin', () => {

const addCalls = $addEventListener.mock.calls;

expect(addCalls).toHaveLength(1);
expect(addCalls).toHaveLength(2);
expect($removeEventListener.mock.calls).toContainEqual(addCalls[0]);
});
});
Expand Down

0 comments on commit ccf828c

Please sign in to comment.