Detect if site visit is new with js - javascript

I would like to check if a user who opens my website is new (type in url OR redirect through google) and then display a message.
But when the user browse through the site (subpages like about and so on) this message is not displayed.
But when the user closes the browser and visits (maybe a few mintues later) the website again, the message should be displayed again.
How can I implement something like this in JavaScript?

You could use cookies, localStorage, sessionStorage or the referrer info. Note that all of them have their own pros and cons and there is no 100% reliable way of detecting new visitors.
Using the firstImpression.js library that Nadav S mentioned is probably the easiest way.
To get the message to show up for users closing and reopening the site:
unset your cookie / localStorage data on unload or
use a referrer info or sessionStorage based solution
See these MDN resources for more:
cookie
localStorage
sessionStorage
referrer
Slightly relevant as well: http://www.cookielaw.org/faq/

From the MDN:
Returns the URI of the page that linked to this page.
string = document.referrer;
The value is an empty string if the user navigated to the page
directly (not through a link, but, for example, via a bookmark). Since
this property returns only a string, it does not give you DOM access
to the referring page.
This means:
if (!document.referrer) {
//Direct access
} else {
var referer = document.referrer;
//Request comes from referer
}
If you want to save this state, you need to take a look at cookies.

Quite easily, you want session storage
var hasVisited = sessionStorage.getItem('washere');
if ( ! hasVisited ) {
// do stuff
alert('Welcome, stranger !');
sessionStorage.setItem('washere', true);
}

You can implement this by using cookies.
When the visitor first come to your page, you check if your cookie exist, if not show the message to them and then create the cookie for future pages.

Using cookies is probably your best bet. They are super simple to use too. Just write
if(document.cookie = "HasVisited=true"){
//whatever you want it to do if they have visited
}
else {
document.cookie = "HasVisited=true"
//that just saves to their browser that they have for future reference
}

Related

Pass data between refresh/reload (client side, without server side sessions)

In a singlepage application I'd like to pass sensitive data during a page reload/refresh.
Since the data is sensitive it should not be recovered, for example
when a user leaves the domain and then goes back
when a user closes the user agent and restarts it, restoring the previous session
History
thirdpartypage.com (discard data when moving to here)
mypage.com
thirdpartypage.com (discard data when moving to here)
My approach was store it in the sessionStorage.
// On data generation/update
sessionStorage.setItem("data", "DATA");
// ...
// On load (reload)
var data = sessionStorage.getItem("data")
if (data) {
// Initialize application with data
} else {
// Start without
}
Unfortunately, in the sessionStorage the data persists when moving from my application's domain to a foreign domain (and back or forth to my application's domain).
I also tried storing it in
window.name, but while for Chrome this is acceptable (not persisted across domains), Firefox makes the data accessible at the other domain (IE untested)
a short-lived cookie but I don't find this solution secure
If you have a text input that is populated after the page is loaded, on refreshing the page, the browser will repopulate that field with the previous value. If the user leaves the page and comes back to it(not reload), the field will not be repopulated anymore.
So what you could do is to put the ssensitive information in a hidden text input and fetch it from there, it will be there only if the user has refreshed the page.
There's two distinctively separate issues here to consider:
Sensitive data is left on the computer when a user navigates away from the site without logging out, and then later on somebody else visits the site and stumbles on the previous user's data.
Someone with access to the same computer is actively trying to get their hands on your data, and goes poking around in the browser's sqlite database.
For the first case it would be enough to somehow differentiate between a page reload and a new visitor. Once you know that, you could just wipe sessionStorage for new visitors. document.referrer will tell you if someone is coming in through a link, but it can't tell if somebody typed in the address or if the page was just reloaded. Maybe combined with a short-lived cookie you could come up with a solid strategy.
The second case is more tricky, and I think you'll have to consider if the data in question is that sensitive that someone would go to these lengths. One could also argue that the user should have some responsibility for protecting their data as well. One solution could be to store that data in sessionStorage encrypted, and in window.onbeforeunload store the key in a short lived cookie. If the cookie still exists when the page is loaded you can decrypt the data and resume session, and if not, purge the storage.
I'm not sure if these methods are acceptable to you, but I'm not aware of a better way to achieve this. That's not to say one does not exist. However, if you do choose to go the encryption way, crypto-js is my go-to solution for javascript encryption and hashing.
Here's a pseudocode example:
global var user
when page loads {
encryptionKey = getEncryptionCookie()
if encryptionKey is null {
// No key found, this is a new user
eraseSessionStorage()
user = initNewSession()
} else {
// Cookie found
data = decrypt(getFromStorage('user-data'), encryptionKey)
if data is valid {
user = restoreSession(data)
} else {
// Wrong key, either an anomaly or a hack attempt
eraseSessionStorage()
user = initNewSession()
}
}
user.key = newEncryptionKey()
}
when user does something {
user.data = getNewData()
saveToStorage('user-data', encrypt(user.data, user.key))
}
// ie. window.onbeforeunload in JS
when user leaving {
// the validity has to be long enough to last
// through a refresh, but short enough so no one
// can re-enter the site without the user noticing
setEncryptionCookie(user.key, 10 seconds)
}
This way the data is never saved unencrypted, so even if somebody manages to grab it from the sessionStorage it's useless, provided of course that you generate secure keys. Maybe use the mouse position as a seed for a randomizer function?

js function to go back in browser history to last browsed page of specific domain?

I need the js function to go back in history to the last pages used in a specific domain.
reason: I send people to a subdomain to see specific content-galleries (gallery.mydomain.xyz/#1etc). I need them to return to the last page where they left of from the specific tld (mydomain.xyz/pageX) after having clicked through a number of images/videos there at subdomain...
is this possible? any ideas?
thx!
It's not possible using the built-in browser history, no, because your access to that from JavaScript is close to non-existent.
What you can do instead is save the location you want to take them back to in, say, session storage (use local storage instead if this is in a different window), and then link back to that page.
More about session storage / local storage in the web storage spec, but the short version is that it stores strings in a storage area specific to your origin, so for instance:
localStorage.setItem("last-location", "foo");
...stores "foo" in local storage for your origin, with the key "last-location". You can then use getItem to get it later when you need it:
var lastLocation = localStorage.getItem("last-location");
you could use a simple get/post variable to tell where the user is coming from and store that in a session variable for later use when the user is to be returned. As far as I know you cant access the users browsing history from the browsing client with Javascript as its a violation of the sandbox design but that may have changed recently
thx both of you for the quick answer!
... I kind of see, not being a versatile coder myself. but I get the problem involved. and see session-storage is where I want to look at then...
I will have to make this a coding job given my non-skills here :-}
but now I know what to ask for. thx again.

How to add cookie on click in java script

How to add cookie on click in java script? On click I am calling linkedin authentication page..once authenticated I want to return back to the page where I called authentication. I want to store continue url in cookie and pass it..can anyone suggest?
Unless you want to track which pages a user logs in from, I'd suggest using sessionStorage instead of a Cookie. sessionStorage has the added benifit of clearing when the browser is closed, so it is less likely you'll get items left over from previous times you were on the website. To navigate or get the current URL, use window.location.
Say you have your log in link
<a id="foo" href="some_link_that_sends_you_to_login">click</a>
Then you could add an event listener to it such as
document.getElementById('foo').addEventListener(
'click',
function () {
sessionStorage.setItem('last_seen_url', window.location.href);
}
);
Next, on your return page you can get this information back with
var goToURL = sessionStorage.getItem('last_seen_url') || '/';
sessionStorage.removeItem('last_seen_url'); // always clean up after yourself
window.location.href = goToURL;
It would be similar with cookies, using the document.cookie, but JavaScript does not provide a good native interface for this. You'll need to implement something yourself, such as the example on MDN. Remember that all cookie data gets sent to the server with every page request, so you'll be generating more overhead for each thing stored as a cookie.

Redirect based on last visited website

At the moment i'm trying to make a new script that is based on the last visited website of the user. If last visited website is x, then it needs to redirect to another page.
Example:
User clicks on a link on my Facebook fan-page and lands on the homepage. The Javascript now needs to take an action and redirect the user to another page. But only if the user came from http://facebook.com/[fanpage]
Is it possible to create something like this in Javascript?
Thanks a lot,
You could use document.referrer like this:
if ('http://facebook.com/[fanpage]' == document.referrer) {
location.href = 'new_destination.html';
}
If Facebook doesn't do some kind of referrer blocking, then use document.referrer to get the referring page.
(It sounds like that might be something better accomplished server-side, though, in which case you would use the Referer [sic] header.)
I wouldn't rely on referrers sent by the browser. They can be turned off.
Why don't you pass a special parameter in your URL?
http://www.example.com/?fromFb=1

Removing querystrings from the URL before page refresh

After a new user signs up, I need to redirect the user to the home page and display a twitter-style welcome message. I initially tried using the jquery cookie plugin to store my message and display it on the redirected page if the cookie is present, but the problem was that it didn't work across all browsers. Firfox on Safari does not delete the cookie, so the message keeps showing everytime the browser is refreshed. Here's the code:
if ($.cookie("message")) {
TwentyQuestions.Common.ShowMessageBar($.cookie("message"), 7000);
$.cookie('message', "any_value", { expires: -10 })
}
So I decided to use querystring instead, but now the problem is similar. When the home page load, the query string is detected and the message is displayed. But how do I remove the querystring from the URL so that the message doesn't show everytime the page is refreshed?
Thanks!
Could you do:
window.location.href = window.location.href.split('?')[0];
It works, but I'm not for sure if this is what you are looking for?
Maybe the problem is you're trying to do everything on the client side. Instead you should set a persistent cookie associated with the user. Then in the back-end, the first time the homepage is displayed to this user, show you welcome message. Also clear whatever "first time user" flag for this user on the server side. Then the next time the user visits this page they won't see the message.
You can also do a SO like thing where if a user visits your website and the cookie doesn't exist, you can display the "Welcome first time user" message.
Instead of using querystring you can use hash.
Redirect to home page with a special hash and when entering, just remove it.
Something like:
if(document.location.hash == '<special hash>') {
TwentyQuestions.Common.ShowMessageBar(...);
document.location.hash='';
}
location = location.pathname + location.hash
This will of course lose any POST data, but if you've got a query string, they probably arrived at your site via GET anyway.
It should have no effect if the location has no query component.
You can do this with cookies but you have to delete the cookie properly. Setting an expiry date in the past works with some browsers but not others as you've found, the proper way to delete a cookie with the jQuery cookie plugin is to send in a null; from the fine manual:
#example $.cookie('the_cookie', null);
#desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain used when the cookie was set.
So delete it with this:
$.cookie('message', null);
and the cookie approach should work fine.

Categories

Resources