I was curious what the best way is to add Segment to Webflow. I struggled to find an answer, so I figured out an easy way to do it and thought I’d share.
Step 1: Copy segment code
Copy the segment javascript snippet, replace YOUR_WRITE_KEY with your write key from your segment account.
Then paste that segment on Webflow. To do this, go to your project’s settings → custom code, and paste it in the head section.
Step 2: Add custom script
On the same project settings screen from Step 1, paste the following code snippet in the footer section, not head:
<script>
$(document).ready(function() {
$('[data-analytics]').on('click', function(e) {
var properties
var event = $(this).attr('data-analytics')
$.each(this.attributes, function(_, attribute) {
if (attribute.name.startsWith('data-property-')) {
if (!properties) properties = {}
var property = attribute.name.split('data-property-')[1]
properties[property] = attribute.value
}
})
analytics.track(event, properties)
})
})
</script>
Step 3. Almost there! Configure elements to track.
Open your project’s designer on webflow. Click any element that you want to track when it gets clicked (for instance, a button that adds to cart or similar). Click that element’s settings. You should see something like this:
(click the image to see the whole thing)
Add a data-analytics
attribute, and make its value the event
you want to be sent to segment.
You can optionally add as many properties as you want by adding other attributes like this:
data-property-custom
, as shown in the pic.
That’s all.
If you want to see what’s being sent to segment, paste this line below analytics.track(event, properties)
from step 2:
console.log('segment:', { event: event, properties: properties })