Check for presence of a cookie and re-direct page

Hello, I need help with a piece of code:

  1. Check of presence of a cookie
  2. If cookie is not present, re-direct to a specific URL (stay on the page/do nothing if the cookie is there).

I assume it’s JS that can do that, but would appreciate help with this since I don’t know JS.

Many thanks!

Hi,

JS can do that, but this shouldn’t be relied on in so far that a user can disable JavaScript, not be redirected and view whatever content you are wishing them not to see.

That said, what have you tried? Can you show us some code?

Here are the pieces of the puzzle you will need:

Thank you for your reply.

So far I tried the following, but it seems it always re-directs even if the cookie exists. Any ideas?

<script type="text/javascript">
  // Confirm that cookie does not exist
if (document.cookie.indexOf('wf_auth_page') == -1 ) {
  // Re-direct to this page
  window.location = "http://www.google.com";
}
</script>

Also, would it be better to use window.location.replace istead?

User strict comparison operator, because -1 is truthy value, -1 will coerce to true.
if (document.cookie.indexOf('wf_auth_page') === -1 )

And always use strict comparison operator (===).

1 Like

If you use the library I linked to, you can do:

const cookieExists = Cookies.get('wf_auth_page');

if (!cookieExists) {
   window.location = "http://www.google.com";
}

Thank you!

You can check if your cookies exist or not by:

document.cookie.match(/^(.; )?\swf_auth_page\s*=\s*[^;]+(.*)?$/)

Then write your condition according to it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.