samzibizi
samzibizi

Reputation: 31

Show DIV to users who came from Facebook only

I'm wanting to show a specific DIV to users on a product page, only if they've arrived from Facebook.

At the moment I'm using this to confirm that they came from Facebook:

var ref = document.referrer;

if (ref.match(/^https?:\/\/([^\/]+\.)?facebook\.com(\/|$)/i)){
    console.log('User arrived from Facebook')
    } else  {
        console.log('User DID NOT arrive from Facebook')
    }

That seems to work well, but doesn't work if they visit another page first. So it recognises they came from FB if they go directly to the Product Page, however if someone came to the Homepage from FB first and then visited the Product Page, they are not recognised.

Upvotes: 3

Views: 89

Answers (1)

Script47
Script47

Reputation: 14550

A suggestion could be keep a flag using localStorage, so when the user visits any part of your website for the first time check the referrer as you are doing but add this snippet on if the referrer check out as Facebook,

localStroage.setItem('from_facebook', true);

Then on your products page check if that key exists,

if (localStorage.getItem('from_facebook') !== null) {
    /** Show DIV. **/
}

Obviously now it would show it even if they don't come from Facebook (meaning if they've come once, then they'll always see it), so what you can do is add the following snippet on your products page once the div is shown,

localStorage.removeItem('from_facebook');

Now it will show the div and then the from_facebook will be removed from the storage so now it depends on each requests.

Upvotes: 1

Related Questions