Skip to content

Commit

Permalink
feat: allow config of before_send function to edit or reject events (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
pauldambra authored Nov 19, 2024
1 parent 5d8b45c commit f4da6c8
Show file tree
Hide file tree
Showing 21 changed files with 941 additions and 364 deletions.
48 changes: 48 additions & 0 deletions cypress/e2e/before_send.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/// <reference types="cypress" />

import { start } from '../support/setup'
import { isArray } from '../../src/utils/type-utils'

describe('before_send', () => {
it('can sample and edit with before_send', () => {
start({})

cy.posthog().then((posthog) => {
let counter = 0
const og = posthog.config.before_send
// cypress tests rely on existing before_send function to capture events
// so we have to add it back in here
posthog.config.before_send = [
(cr) => {
if (cr.event === 'custom-event') {
counter++
if (counter === 2) {
return null
}
}
if (cr.event === '$autocapture') {
return {
...cr,
event: 'redacted',
}
}
return cr
},
...(isArray(og) ? og : [og]),
]
})

cy.get('[data-cy-custom-event-button]').click()
cy.get('[data-cy-custom-event-button]').click()

cy.phCaptures().should('deep.equal', [
// before adding the new before sendfn
'$pageview',
'redacted',
'custom-event',
// second button click only has the redacted autocapture event
'redacted',
// because the second custom-event is rejected
])
})
})
7 changes: 4 additions & 3 deletions cypress/support/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ Cypress.Commands.add('posthogInit', (options) => {
cy.posthog().invoke('init', 'test_token', {
api_host: location.origin,
debug: true,
_onCapture: (event, eventData) => {
$captures.push(event)
$fullCaptures.push(eventData)
before_send: (event) => {
$captures.push(event.event)
$fullCaptures.push(event)
return event
},
opt_out_useragent_filter: true,
...options,
Expand Down
9 changes: 5 additions & 4 deletions playground/copy-autocapture/demo.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@
loaded: function(posthog) {
posthog.identify('test')
},
_onCapture: (event, eventData) => {
if (event === '$copy_autocapture') {
const selectionType = eventData.properties['$copy_type']
const selectionText = eventData.properties['$selected_content']
before_send: (event) => {
if (event.event === '$copy_autocapture') {
const selectionType = event.properties['$copy_type']
const selectionText = event.properties['$selected_content']
document.getElementById('selection-type-outlet').innerText = selectionType
document.getElementById('selection-text-outlet').innerText = selectionText
}
return event
},
})
</script>
Expand Down
Loading

0 comments on commit f4da6c8

Please sign in to comment.