|
14 | 14 | * limitations under the License.
|
15 | 15 | */
|
16 | 16 |
|
| 17 | +import { classifyPII, getUserData } from './utils'; |
| 18 | + |
17 | 19 | ( ( mc4wp ) => {
|
18 | 20 | if ( ! mc4wp ) {
|
19 | 21 | return;
|
20 | 22 | }
|
21 | 23 |
|
22 |
| - mc4wp.forms.on( 'subscribed', () => { |
| 24 | + mc4wp.forms.on( 'subscribed', ( mc4wpForm, data ) => { |
| 25 | + const gtagUserDataEnabled = global._googlesitekit?.gtagUserData; |
| 26 | + |
| 27 | + const userData = gtagUserDataEnabled |
| 28 | + ? getUserDataFromForm( mc4wpForm.element, data ) |
| 29 | + : null; |
| 30 | + |
23 | 31 | global._googlesitekit?.gtagEvent?.( 'submit_lead_form', {
|
24 | 32 | event_category: 'mailchimp',
|
| 33 | + ...( userData ? { user_data: userData } : {} ), |
25 | 34 | } );
|
26 | 35 | } );
|
27 | 36 | } )( global.mc4wp );
|
| 37 | + |
| 38 | +/** |
| 39 | + * Extracts and classifies user data from a Mailchimp form submission. |
| 40 | + * |
| 41 | + * @since n.e.x.t |
| 42 | + * |
| 43 | + * @param {HTMLFormElement} form The submitted form element. |
| 44 | + * @param {Object} data The submitted form's data. |
| 45 | + * @return {Object|undefined} A user_data object containing detected PII (address, email, phone_number), or undefined if no PII found. |
| 46 | + */ |
| 47 | +function getUserDataFromForm( form, data ) { |
| 48 | + // eslint-disable-next-line sitekit/acronym-case |
| 49 | + if ( ! form || ! ( form instanceof HTMLFormElement ) ) { |
| 50 | + return undefined; |
| 51 | + } |
| 52 | + |
| 53 | + const detectedFields = Object.entries( data ) |
| 54 | + .map( ( [ name, value ] ) => { |
| 55 | + // Mailchimp joins the individual name fields into a single field "NAME", |
| 56 | + // but still provides the individual values in the data object, so we skip them. |
| 57 | + if ( 'NAME' in data && ( name === 'FNAME' || name === 'LNAME' ) ) { |
| 58 | + return null; |
| 59 | + } |
| 60 | + |
| 61 | + const input = form.querySelector( `[name='${ name }']` ); |
| 62 | + |
| 63 | + const type = input?.type; |
| 64 | + |
| 65 | + const label = input?.id |
| 66 | + ? form.querySelector( `label[for='${ input?.id }']` ) |
| 67 | + ?.textContent |
| 68 | + : undefined; |
| 69 | + |
| 70 | + return classifyPII( { |
| 71 | + type, |
| 72 | + label, |
| 73 | + name, |
| 74 | + value, |
| 75 | + } ); |
| 76 | + } ) |
| 77 | + .filter( Boolean ); |
| 78 | + |
| 79 | + return getUserData( detectedFields ); |
| 80 | +} |
0 commit comments