多亏了这篇很棒的帖子,我才明白出了什么问题,并将这些想法应用到.NET
. 主要思想是捕获amp-analytics
配置对象(JSON 格式)并将其替换为我自己的(clientId
内部)。
首先我创建HttpHandler
''//.VB
Namespace AmpHandlers
Public Class AmpConfig
Implements IHttpHandler
Private Const unixStart As DateTime = #1/1/1970# ''//start of epoc
Public ReadOnly Property IsReusable As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Public Sub ProcessRequest(context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.Clear()
''//ecpected request
''// https : //mydomain.com/gtm-amp.json?id=GTM-zzzzzz>m.url=SOURCE_URL
If String.IsNullOrEmpty(context.Request.QueryString("id")) OrElse context.Request.QueryString("id") <> "GTM-zzzzzz" Then
''//no answer
context.Response.End()
Return
End If
Dim clientId As String = ""
If context.Request.Cookies("_ga") IsNot Nothing Then
Dim ga As String = context.Request.Cookies("_ga").Value ''//GA1.2.12321354.1507250223
clientId = Regex.Match(ga, "(\d+?\.\d+?$)").Groups(1).Value
Else
Dim rand As New Random()
''//Majic 2147483647 is upper limit of Google's random part of _ga cookie
''//The second part is Unix time, in seconds
clientId = rand.Next(2147483647) & "." & CInt(DateTime.UtcNow.Subtract(unixStart).TotalSeconds)
End If
''//Set cookie and response headers
context.Response.ContentType = "application/json" '; charset=UTF-8
context.Response.SetCookie(New HttpCookie("_ga") With {.Value = "GA1.2." & clientId,
.Path = "/", .Domain = context.Request.Url.Host, .Expires = DateTime.UtcNow.AddYears(2)
})
context.Response.AddHeader("Access-Control-Allow-Origin", "https://mydomain-com.cdn.ampproject.org")
context.Response.AddHeader("Access-Control-Expose-Headers", "AMP-Access-Control-Allow-Source-Origin")
context.Response.AddHeader("AMP-Access-Control-Allow-Source-Origin", "https://" & context.Request.Url.Host)
context.Response.AddHeader("Access-Control-Allow-Source-Origin", "https://" & context.Request.Url.Host)
context.Response.AddHeader("Access-Control-Allow-Credentials", "true")
context.Response.AddHeader("Content-Disposition", "attachment; filename=""GTM-NZPM27T.json""")
context.Response.AddHeader("cache-control", "no-cache, no-store, must-revalidate")
''//https://www.googletagmanager.com/amp.json?id=GTM-zzzzzz>m.url=SOURCE_URL response is saved locally and edited
''//possibly it is not the best colution
Dim sr As New IO.StreamReader(context.Server.MapPath("~/amp-gtm.config"))
Dim str As String = sr.ReadToEnd()
str = str.Replace("[[clientId]]", clientId)
context.Response.Write(str)
context.Response.Flush()
context.Response.End()
End Sub
End Class
End Namespace
接下来我在web.config
.
<handlers>
<add name="amp-gtm" verb="GET" path="gtm-amp.json" type="AmpHandlers.AmpConfig" resourceType="Unspecified"/>
</handlers>
最后放入amp-analytics
标签中。
<amp-analytics config="https : //mydomain.com/gtm-amp.json?id=GTM-zzzzzz>m.url=SOURCE_URL" data-credentials="include"></amp-analytics>
现在,来自缓存和非缓存 AMP 页面的所有点击都会显示organic/google
。