简体   繁体   中英

Get cookie on first load

So I created this new thread for this one since it was so bad explained, but was told to edit this one:

New Text

I need to receive a user_id from a external website. I only need to receive this if the user come to site A from site B. So when he does that I then save that user_id in a cookie, that part is working fine. But I also need to get the value of the cookie when he first land on the page, so let me try to explain how I have done this:

First I look at if user is coming from another domain:

var ownDomain = location.hostname,
    referrerDomain = document.referrer.split('/')[2],
    author = '';

if ( ownDomain != referrerDomain) {
  var script = document.createElement('script');
  script.src = '//javascript.mamp/json/?callback=setAuthorCookie';
  document.getElementsByTagName('head')[0].appendChild(script);
}

If he does that, then we insert a javascript which calls the callback setAuthorCookie() , which looks like this:

function setAuthorCookie( data ) {
  var exdate = new Date(),
      exdays = 1,
      value = data['userId'],
      cookie = 'partnerOptimizerId',
      exdate = new Date();

   author = value;

   exdate.setDate(exdate.getDate() + exdays);
   var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
   document.cookie=cookie + "=" + c_value;
}

Now as you can see I set the author value inside that function, so I should be able to console.log out the value of author and get the correct value:

console.log( author )

I return nothing, which is kind of where Im stuck right now. I guess it is because that some how setAutorCookie runs after I console.log( author ) , but I was hoping someone could help me on this, is it because author is a local variable in setAuthorCookie ?

After some testing I can see that setAuthorCookie runs after the last console.log() and that is why it is empty but can somebody help with how I change that ?

You're only returning something from getCookie() under certain conditions:

  if (x==cookie)
  {
    return unescape(y);
  }

So if x != cookie, your function does not have a return. Therefore when you say var author = getCookie( 'partnerOptimizerId' ); , but getCookie() doesn't return anything, author will be undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM