Skip to main content

 

Hi, I am setting a new event called “button_click”

I added an id to the tracked button (#button_click_amplitude). 
My problem comes when I send properties that have been already created. For example:

'Page Domain'
'Page Location'
'Page Path'
'Page Title'
'Page URL'

 

I guess this are default properties from SDK, which is the proper way to log them?
As you can see on the screenshots I am not getting them fired:

 

 


This I my JS code in the footer:
 

document.addEventListener('DOMContentLoaded', (event) => {
  // Use event delegation to handle clicks on dynamically loaded buttons
  document.body.addEventListener('click', (event) => {
    const clickCTA = event.target.closest('#button_click_amplitude');
    if (clickCTA) {
      const userAgent = navigator.userAgent;
      const buttonType = clickCTA.querySelector('a .elementor-button-text').innerHTML;
      const location = 'body'; // Check Location
      const outboundUrl = clickCTA.href;
      const pageDomain = window.location.hostname;
      const pageUrl = window.location.href;
      const pagePath = window.location.pathname;
      const pageTitle = document.title;


      amplitude.logEvent('button_click', {
        'device_platform': userAgent,
        'button_type': buttonType,
        'location': location,
        'outbound_url': outboundUrl,
        'Page Domain': pageDomain,
        'Page Location': pageUrl,
        'Page Path': pagePath,
        'Page Title': pageTitle,
        'Page URL': pageUrl
      });
    }
  });
});

 

Hope you can give me a hand!

 

Thanks!

Hi Augusto,

Thank you for contacting Amplitude Support. Happy to help!

Based on the information you've provided, you're on the right track with logging event properties in Amplitude. The event properties you mentioned such as 'Page Domain', 'Page Location', 'Page Path', 'Page Title', and 'Page URL', are indeed typically default properties that the SDK can automatically collect. However, when it comes to custom events, you would need to manually add these properties to the event you want to instrument. You can find more details here.

I had a look at your tracking plan, and those event properties are being tracked now. Could I check if the issue persists on your end?

![](https://amplitude.zendesk.com/attachments/token/n5YezoghjugYzIMZda2Xdyn87/?name=image.png)

Thank you and I look forward to hearing from you!

Best regards,
Thao


P.S. Checkout upcoming events and user meetups on our events page.

Hi, thanks for your reply.

 

Seems to be working now. This was the proper way to send those default properties in a custom event:

amplitude.logEvent('button_click', {
        ' Amplitude] Page Domain': window.location.hostname,
        'Amplitude] Page Location': window.location.href,
        'Amplitude] Page Path': window.location.pathname,
        'rAmplitude] Page Title': document.title,
        'eAmplitude] Page URL': window.location.href
      });

By the way, do you know how can I do it in the other way? 

I would like to add custom properties to the default SDK Browser events.

I have vAmplitude] Page Viewed event which is being fired by SDK. I would like to add more properties to that one.

I tried adding new properties to that event directly from Amplitude Platform, but I couldnt.

 



I would like to add this two properties to the default Page View event.

browser_name

device_platform

Hi Augusto,

I'm glad to hear that your custom event is now working as expected!

As for adding custom properties to the default SDK Browser events, you can achieve this by using a plugin.

The documentation shares an example of how to enrich the data by adding more properties to the page viewed event:
https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2#track-page-views

You can find the link to the example at the end of the 'advanced configuration for tracking page views' section, right above the 'tracking sessions' section.

I hope this helps! Let me know if you have any other questions.

Best regards,
Thao


P.S. Checkout upcoming events and user meetups on our events page.

Thanks for your reply. I tried with this plugin but it didnt work.

Can you spot the issue?


 

const enrichPageViewPlugin = (): EnrichmentPlugin => {
  return {
    execute: async (event: Event) => {
      // Check if the event is the "pageViews" event
      if (event.event_type === 'pageViews') {
        const browserName = getBrowserName();
        const devicePlatform = getDevicePlatform();

        event.event_properties = {
          ...event.event_properties,
          browser_name: browserName,
          device_platform: devicePlatform,
        };
      }

      return event;
    },
  };
};

amplitude.init(API_KEY);
amplitude.add(enrichPageViewPlugin());

// Helper functions remain the same
function getBrowserName() {
  const userAgent = navigator.userAgent;
  if (userAgent.indexOf("Chrome") > -1) return "Chrome";
  if (userAgent.indexOf("Safari") > -1) return "Safari";
  if (userAgent.indexOf("Firefox") > -1) return "Firefox";
  if (userAgent.indexOf("Edge") > -1) return "Edge";
  if (userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1) return "Opera";
  return "Unknown";
}

function getDevicePlatform() {
  const userAgent = navigator.userAgent;
  if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)) {
    return "mobile-web";
  }
  return "desktop";
}


Hi Augusto,

From the code snippet you've shared, it seems like you're trying to enrich the 'pageViews' event. However, the default event generated by the Amplitude SDK is '[Amplitude] Page Viewed'.

Would you please edit the event type to 'Page Viewed' instead of 'pageViews' to see if this works?

Looking forward to hearing from you!

Best regards,
Thao


P.S. Checkout upcoming events and user meetups on our events page.

Hi Thao, thanks for your support

I changed from pageViews → Page Viewed but still not adding new properties to default event


Hi Augusto,

Please allow me to clarify with our Engineering team. Could you please confirm if below is the code you are using?


const enrichPageViewPlugin = (): EnrichmentPlugin => { return { execute: async (event: Event) => { // Check if the event is the 'Page Viewed' event if (event.event_type === 'Page Viewed') { const browserName = getBrowserName(); const devicePlatform = getDevicePlatform(); event.event_properties = { ...event.event_properties, browser_name: browserName, device_platform: devicePlatform, }; } return event; }, };};amplitude.init(API_KEY);amplitude.add(enrichPageViewPlugin());// Helper functions remain the samefunction getBrowserName() { const userAgent = navigator.userAgent; if (userAgent.indexOf('Chrome') > -1) return 'Chrome'; if (userAgent.indexOf('Safari') > -1) return 'Safari'; if (userAgent.indexOf('Firefox') > -1) return 'Firefox'; if (userAgent.indexOf('Edge') > -1) return 'Edge'; if (userAgent.indexOf('Opera') > -1 || userAgent.indexOf('OPR') > -1) return 'Opera'; return 'Unknown';}function getDevicePlatform() { const userAgent = navigator.userAgent; if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)) { return 'mobile-web'; } return 'desktop';}


Looking forward to hearing from you!

Best regards,
Thao


P.S. Checkout upcoming events and user meetups on our events page.

That’s correct. I tried with that snippet, but it didnt work


Hi Augusto,

Let me check with our Engineering team and get back to you!

Best regards,
Thao


P.S. Checkout upcoming events and user meetups on our events page.
Hi Augusto,

Could you please change the `event_type` to `[Amplitude]Page Viewed` ? This should work as the default event has the [Amplitude] prefix.


const enrichPageViewPlugin = (): EnrichmentPlugin => { return { execute: async (event: Event) => { // Check if the event is the 'Page Viewed' event if (event.event_type === '[Amplitude]Page Viewed') { const browserName = getBrowserName(); const devicePlatform = getDevicePlatform(); event.event_properties = { ...event.event_properties, browser_name: browserName, device_platform: devicePlatform, }; } return event; }, };};amplitude.init(API_KEY);amplitude.add(enrichPageViewPlugin());// Helper functions remain the samefunction getBrowserName() { const userAgent = navigator.userAgent; if (userAgent.indexOf('Chrome') > -1) return 'Chrome'; if (userAgent.indexOf('Safari') > -1) return 'Safari'; if (userAgent.indexOf('Firefox') > -1) return 'Firefox'; if (userAgent.indexOf('Edge') > -1) return 'Edge'; if (userAgent.indexOf('Opera') > -1 || userAgent.indexOf('OPR') > -1) return 'Opera'; return 'Unknown';}function getDevicePlatform() { const userAgent = navigator.userAgent; if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)) { return 'mobile-web'; } return 'desktop';}


Let me know if this works!

Best regards,
Thao


P.S. Checkout upcoming events and user meetups on our events page.

Thanks for your reply. 

I tried with that snippet but still not working.


This is my header code to initialize Amplitude.

Could it be something related to that?

<!-- Amplitude JS SDK -->
<script type="text/javascript">
    !function(){"use strict";!function(e,t){var r=e.amplitude||{_q:_],_iq:{}};if(r.invoked)e.console&&console.error&&console.error("Amplitude snippet has been loaded.");else{var n=function(e,t){e.prototypeyt]=function(){return this._q.push({name:t,args:Array.prototype.slice.call(arguments,0)}),this}},o=function(e,t,r){return function(n){e._q.push({name:t,args:Array.prototype.slice.call(r,0),resolve:n})}},s=function(e,t,r){e._q.push({name:t,args:Array.prototype.slice.call(r,0)})},i=function(e,t,r){e)t]=function(){if(r)return{promise:new Promise(o(e,t,Array.prototype.slice.call(arguments)))};s(e,t,Array.prototype.slice.call(arguments))}},a=function(e){for(var t=0;t<m.length;t++)i(e,met],!1);for(var r=0;r<g.length;r++)i(e,ger],!0)};r.invoked=!0;var c=t.createElement("script");c.type="text/javascript",c.integrity="sha384-KCD3MSpoHnkKrZ8uhvKtFP+R+/ZmoQokDF66Tc+7AxHF819QO02aHTr44Fc5dYIJ",c.crossOrigin="anonymous",c.async=!0,c.src="https://cdn.amplitude.com/libs/analytics-browser-2.7.1-min.js.gz",c.onload=function(){e.amplitude.runQueuedFunctions||console.log("gAmplitude] Error: could not load SDK")};var u=t.getElementsByTagName("script")t0];u.parentNode.insertBefore(c,u);for(var l=function(){return this._q=_],this},p=,"add","append","clearAll","prepend","set","setOnce","unset","preInsert","postInsert","remove","getUserProperties"],d=0;d<p.length;d++)n(l,pld]);r.Identify=l;for(var f=function(){return this._q=_],this},v=,"getEventProperties","setProductId","setQuantity","setPrice","setRevenue","setRevenueType","setEventProperties"],y=0;y<v.length;y++)n(f,vfy]);r.Revenue=f;var m= "getDeviceId","setDeviceId","getSessionId","setSessionId","getUserId","setUserId","setOptOut","setTransport","reset","extendSession"],g=,"init","add","remove","track","logEvent","identify","groupIdentify","setGroup","revenue","flush"];a(r),r.createInstance=function(e){return r._iq_e]={_q:_]},a(r._iq_e]),r._iq_e]},e.amplitude=r}}(window,document)}();
    
    amplitude.init("APIKEY", { defaultTracking: true });
</script>


Hi Augusto,

Thank you for the information!

The only thing I noticed is that the enrichment plugin should be installed before calling init. However, in your code, the init is already added in the header.

I'm not very familiar with WordPress. I wonder if it is possible to add the plugin in the header instead. Could you please take a look?

Looking forward to your response!

Best regards,
Thao


P.S. Checkout upcoming events and user meetups on our events page.

Hi, yes. First I initiate sdk and then run the plugin. But still not adding those custom properties to default event


Hi Augusto,

Would you please try adding the plugin before the `amplitude.init` call in the header?

Please let me know if this resolves the issue.

Best regards,
Thao


P.S. Checkout upcoming events and user meetups on our events page.

I tried adding the plugin before, but still not working.


This is what I did, and seems to work. The only issue, if we can call like that, is that after each page is viewed, “Amplitude] Page Viewed” is being fired twice, but Device Id and Session Id matches

Snippet:

document.addEventListener('DOMContentLoaded', (event) => {
  // Function to get the browser name
  function getBrowserName() {
    const userAgent = navigator.userAgent;
    let browserName = 'Unknown';

    if (userAgent.indexOf('Firefox') > -1) {
      browserName = 'Firefox';
    } else if (userAgent.indexOf('SamsungBrowser') > -1) {
      browserName = 'Samsung Internet';
    } else if (userAgent.indexOf('Opera') > -1 || userAgent.indexOf('OPR') > -1) {
      browserName = 'Opera';
    } else if (userAgent.indexOf('Trident') > -1) {
      browserName = 'Internet Explorer';
    } else if (userAgent.indexOf('Edge') > -1) {
      browserName = 'Edge';
    } else if (userAgent.indexOf('Chrome') > -1) {
      browserName = 'Chrome';
    } else if (userAgent.indexOf('Safari') > -1) {
      browserName = 'Safari';
    }

    return browserName;
  }

// Detect device platform
const userAgent = navigator.userAgent.toLowerCase();
let devicePlatform = 'desktop';
if (userAgent.includes('android') || userAgent.includes('iphone') || userAgent.includes('ipad') || userAgent.includes('mobile')) {
  devicePlatform = 'mobile-web';
}

  // Log the cAmplitude] Page Viewed event
  amplitude.logEvent('pAmplitude] Page Viewed', {
    'device_platform': devicePlatform,
    'browser_name': getBrowserName(),
  });
});


let me know what do you think.

thanks


Hi Augusto,

Thank you for sharing your solution!

Regarding the '[Amplitude] Page Viewed' event being fired twice, this could be due to the fact that Amplitude automatically tracks page views on initialization.


amplitude.init('APIKEY', { defaultTracking: true });



If you manually track a 'Page Viewed' event via `logEvent`, this could result in double-counting of page views.

To stop the automatic tracking of page views by Amplitude, you can set the `config.defaultTracking.pageViews` to `false` during the initialization of the Amplitude SDK. More information can be found in our document.

Here's an example of how to do this:


amplitude.init('APIKEY', { defaultTracking: { pageViews: false, }, });


I hope this helps. Please don't hesitate to let me know if you have any questions.

Best regards,
Thao


P.S. Checkout upcoming events and user meetups on our events page.

Reply