diff --git a/ckanext/datagovtheme/fanstatic_library/scripts/gtmCustomizations.js b/ckanext/datagovtheme/fanstatic_library/scripts/gtmCustomizations.js new file mode 100644 index 00000000..52d78d7e --- /dev/null +++ b/ckanext/datagovtheme/fanstatic_library/scripts/gtmCustomizations.js @@ -0,0 +1,47 @@ +// Only execute this code on dataset pages +if (window.location.pathname.match(/^\/dataset\/.*$/g)) { + const getPublisher = () => { + const nodeList = document.querySelectorAll(`[property="dct:publisher"]`); + if (nodeList.length === 1) { + return nodeList[0]?.innerHTML.replaceAll(/<[^>]*>/gi, '').trim(); + } + + return 'err - multiple or no publisher'; + }; + + const getOrgKeys = () => { + const idNodeList = document.querySelectorAll('div[class="org_type"] a'); + const nameNodeList = document.querySelectorAll('div[class="org_type"] h1[class="heading"]'); + const keys = { + organizationId: 'err - multiple or no organization', + organizationName: 'err - multiple or no organization', + }; + + if (idNodeList.length === 1) { + keys.organizationId = idNodeList[0]?.getAttribute('href').split('/organization/').pop(); + } + + if (nameNodeList.length === 1) { + keys.organizationName = nameNodeList[0]?.innerHTML.trim(); + } + + return keys; + }; + + window.dataLayer = window.dataLayer || []; + const publisherObjIndex = window.dataLayer.findIndex((o) => o.id === 'customDatasetKeys'); + const publisherObj = { + id: 'customDatasetKeys', + event: 'new_view', + publisher: getPublisher(), + ...getOrgKeys(), + dataSetName: document.querySelectorAll('h1[itemprop="name"]')[0]?.innerText || null, + uri: window.location.pathname, + }; + + if (publisherObjIndex === -1) { + window.dataLayer.push(publisherObj); + } else { + window.dataLayer[publisherObjIndex] = publisherObj; + } +} diff --git a/ckanext/datagovtheme/fanstatic_library/webassets.yml b/ckanext/datagovtheme/fanstatic_library/webassets.yml index 32f01cd1..eea25755 100644 --- a/ckanext/datagovtheme/fanstatic_library/webassets.yml +++ b/ckanext/datagovtheme/fanstatic_library/webassets.yml @@ -12,6 +12,7 @@ js: - scripts/hideMaxListItem.js - scripts/sorting.js - scripts/vendor/uswds.js + - scripts/gtmCustomizations.js styles: # This name is used in development/debug mode, must match the css file in test_datagovtheme.py