This is a useful function I wrote to capture what keywords a user typed into the search engines before landing on one of my site's pages.
We’ll extract the keywords from the Referrer url. This code is able to read the search terms coming from theses search engines : Google, Yahoo, Live, MSN, ASK, Bing, Twitter and Babylon search.
public static string Get_Search_terms()
{
string Ref = ((System.Web.HttpContext.Current.Request.UrlReferrer != null) ? System.Web.HttpContext.Current.Request.UrlReferrer.ToString():"");
if (Ref.Contains("google") || Ref.Contains("live.com") || Ref.Contains("msn.com") || Ref.Contains("yahoo") || Ref.Contains("ask.com") || Ref.Contains("bing.com") || Ref.Contains("twitter.com") || Ref.Contains("search.babylon"))
{
int P = Ref.IndexOf("&q=");
if (P < 1) { P = Ref.IndexOf("?q="); }
if (P < 1) { P = Ref.IndexOf("&p="); }
if (P < 1) { P = Ref.IndexOf("?p="); }
if (P > -1)
{
Ref = Ref.Substring(P + 3);
P = Ref.IndexOf("&");
if (P > 0)
{
Ref = Ref.Substring(0, P);
}
Ref = Ref.Replace("+", " ").Trim();
}
}
return HttpUtility.UrlDecode(Ref);
}
Unfortunately, lately Google has changed his behavior, and he’s no longer passing the search terms in referrer for users logged in Google+, instead he send an empty string “q=”.