Skip to content

Track HTTP Referrer on form submits

Camille Roux edited this page Oct 3, 2016 · 2 revisions

Track referrer

You can easily add referrer tracking to your form submits so you know where users came from prior to submitting your form.

In your application controller:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_filter :store_referer

  def store_referer
  	http_referer = request.env['HTTP_REFERER']
  	internal = /^(https?:\/\/)?(www.)?YOUR_DOMAIN.com.*/.match(http_referer)
  	if !internal #ignore internal referers
		session[:referer] = http_referer || 'none'
	elsif session[:referer].nil?
		session[:referer] = http_referer || 'none'
	end
  end
end

Add a hidden field to your mail form:

# Uses simple_form
<%= f.input :referer, input_html: { value: session[:referer] }, as: :hidden %>

Add the attribute to your mail_form model:

class Contact < MailForm::Base
  attribute :name,      :validate => true
  attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  attribute :message
  attribute :referer

  ...
end
Clone this wiki locally