Try our conversational search powered by Generative AI!

Get URL of the first page viewed during session

ZZ
ZZ
Vote:
 

Hi,

I have this requirement to track the event of the first page viewed and the current page URL, and send it to datalayer. Below script would be added to generic layout (shared layout)

<script>  
window.dataLayer.push({

  event: "genericinfo",

  environment: "xx", / Use 'xx' for development and 'pp' if in production

  pageURL: "https://xxx", / The URL of the page

  pageTitle: "", / The title of the current page

  ogLocation: "", / The URL of the first page viewed - should never be changed during the session. Please only update this value if the browser tab was closed.

});
</script>

How can I get the first page viewed and then sent always the same page during the same session ?

#305159
Jul 14, 2023 8:36
Vote:
 

It's not best practise to do it that way. There should be a tag manager, eg. something that is a part of the statistics/tracking system and inserts the correct code for the correct place. This usually handles this kind of stuff.

What you should do is, first of all add checks to see if the window.dataLayer object exists. Otherwise this script will fail, and it can stop script execution on the page and make other functions not working.

For tracking the first page visited, you need to add code that stores this information. You could either store it on the server side in a session variable or a cookie. Or, what I suggest, is to store it in a cookie next to the code for the tracking, so that you have it in one place. So; check the value of the cookie, and if it is empty, save the current page URL to this cookie. To have it stay the same during the session but be a new one on next visit, the cookie should be stored as a session cookie.

#305171
Jul 14, 2023 13:09
Vote:
 

Hi ZZ,

I think you kinda answered you own question.

Session State?

Essientally you can choose a storage mechanism of you choice. When a user visits the site for the first time up date the storage with the value of that page.

On subsequent page visits you check that storage and if it is set use it, otherwise set and use it.

Checkout some of the storage options and comparsions here https://www.sitepoint.com/client-side-storage-options-comparison/.

Paul

#305172
Jul 14, 2023 13:12
Vote:
 

You should really avoid session state as it requires sticky sessions and is not maintained if the user is sent to another server.  You could check for the existance of a `__firstPage` cookie and if it is absent, then create it with the Id of the current page, set it to samesite, secure with lifespan of browser session.  You could then use this when assembling this in your script in your razor file.

#305488
Jul 21, 2023 8:08
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.