Read a cookie on page load

Hello,

I believe (from prior community discussions) that there isn’t a native weweb way to read or set browser cookies on page load to maintain state between visits. Just checking if that is still the case and if anyone has tried doing that with Javascript.

Thanks,
Bill

To clarify, I can use JS (i.e document.cookie=“user=yes”) to set the cookies. I’m not sure how to read it back into a weweb variable on the next page load after a browser exit.

I found it:

  1. Use the ‘Return Value’ action is Step 1 in the ‘On Page Load’ workflow
  2. Set the formula to → document.cookie
  3. On Step 2, assign the output of Step 1 to a weweb variable.

Unfortunately, the output you get is a semi-colon separated string with all the cookies. From there, you have to parse that up to get what you need.

1 Like

Hi @billdonnelly,

In order to maintain state between visits you can use the localstorage feature of your variables. Cookies is more when you want an information to be sent with your requests. If you only need to maintain a front-end state, local storage is the way to go, and the easier one.

1 Like

Thanks Alexis,

If I can describe the use case further, when an existing user makes a return visit to my website after closing the browser, I wanted to be able to know (on page load) that this is an existing user and apply some conditional logic.

Are variables in local storage automatically initialized on page load?

Yes, they are! Variables are initialised before any app/page workflows.

1 Like

Sounds like this would also be the preferred way to build a referral attribution system? For instance, use URL query param with referrer ID, then set a local variable with that ID so that if that user comes back to sign up, I can read the local variable to see who originally referred them?

Is there an expiry time for local variables? Can I set that somewhere?

Any input on a better approach would be appreciated too!

Hi @Alexis , I started with variables, it works fine… but I’m testing with just one user logged.
Variables are shared with all users ? or each has an instance on them ?

Cheers
Patrick

Hi, they are not shared between users, each tabs has its own instance of the app and of the variables. If you use localstorage the states of the variables will be restored when opening in a new tab, that’s all.

1 Like