Skip to content
Open
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
55 changes: 54 additions & 1 deletion assets/js/event-providers/mailchimp.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,67 @@
* limitations under the License.
*/

import { classifyPII, getUserData } from './utils';

( ( mc4wp ) => {
if ( ! mc4wp ) {
return;
}

mc4wp.forms.on( 'subscribed', () => {
mc4wp.forms.on( 'subscribed', ( mc4wpForm, data ) => {
const gtagUserDataEnabled = global._googlesitekit?.gtagUserData;

const userData = gtagUserDataEnabled
? getUserDataFromForm( mc4wpForm.element, data )
: null;

global._googlesitekit?.gtagEvent?.( 'submit_lead_form', {
event_category: 'mailchimp',
...( userData ? { user_data: userData } : {} ),
} );
} );
} )( global.mc4wp );

/**
* Extracts and classifies user data from a Mailchimp form submission.
*
* @since n.e.x.t
*
* @param {HTMLFormElement} form The submitted form element.
* @param {Object} data The submitted form's data.
* @return {Object|undefined} A user_data object containing detected PII (address, email, phone_number), or undefined if no PII found.
*/
function getUserDataFromForm( form, data ) {
// eslint-disable-next-line sitekit/acronym-case
if ( ! form || ! ( form instanceof HTMLFormElement ) ) {
return undefined;
}

const detectedFields = Object.entries( data )
.map( ( [ name, value ] ) => {
// Mailchimp joins the individual name fields into a single field "NAME",
// but still provides the individual values in the data object, so we skip them.
if ( 'NAME' in data && ( name === 'FNAME' || name === 'LNAME' ) ) {
return null;
}

const input = form.querySelector( `[name='${ name }']` );

const type = input?.type;

const label = input?.id
? form.querySelector( `label[for='${ input?.id }']` )
?.textContent
: undefined;

return classifyPII( {
type,
label,
name,
value,
} );
} )
.filter( Boolean );

return getUserData( detectedFields );
}
Loading