How to add cookie on click in java script - javascript

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.

Related

Refreshing a page with cookies in Play

I have a drop-down selection of available languages. Currently, clicking on a language is mapped to a method in controller which updates the Play Session (which is a cookie under the hood) with the selected language and returns index page.
View:
English
Controller:
def setLanguage(language: String): Action[AnyContent] = Action { implicit request =>
val updatedSession = request.session + (("lang", language))
Redirect(routes.Application.index()).withSession(updatedSession)
}
As you can see, I redirect to index page and it's working fine. However, as the language selection is available at all times on my page, it may be clicked from /resource1, /resource2, /resource3 etc. and I would like to refresh that particular view instead of being returned to home page. I cannot simply get request.uri in the controller and refresh whatever it's pointing to because setLanguage() is mapped to its own route, so my request URI is always /language?lang=whatever.
So, how do I know that prior to invoking GET on /language, client was on, say, /items so I can reload items page instead of returning him to home page? Should I send a GET request with resource as a parameter (e.g. ?lang=en&location=items) to know which page to render? Should I make an ajax request and call window.location.reload() on success? Do I even need to go to server or can I simply update the PLAY_SESSION cookie manually from the client?
I'm using Play 2.3.7.
No you cannot update the PLAY_SESSION cookie from the client side, since it is signed by play with the application secret.
So I think the easiest solution would be, as suggested, to send the current resource as parameter and trigger a redirect.
There is an HTTP header called Referer that contains the url from which the request was made. As far as I know it's supported and used by all modern browsers when you navigate from a page to another.
You can simply redirect to that Referer url.
Another solution is to track in a session or a cookie all pages that are accessed by an user, by using some kind of interceptor in Global.scala or a custom Action builder that you use everywhere. Then in case of language change you can simply redirect to the last page that was accessed by the user.

Detect if site visit is new with js

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
}

Differentiate between first download of the page and all subsequent downloads of the same page

I have a static page (by static, I mean html, css and javascript are fixed on the page).
On the server side, I can tell (based on server-side session info) whether this is the first loading of the page or not by a particular user. Now, based on this detail, I want to signal the front end (e.g. by setting something in the response header, maybe?), so that a javascript function on the page can perform some action based on whether this is the first time the user has landed on this page.
The server that actually serves the page is Nginx, and the server that handles the logic, session, etc is Tornado. So presumably I need to do something in tornado, and then instruct nginx to deliver the static page.
Is this doable? If so, what is the most robust way of doing so?
You could achieve this with cookies: http://www.quirksmode.org/js/cookies.html
WIth cookies you would send a specific cookie w/ the response headers on the first view. Then each time the page loads, have your javascript check the specific cookie
Or use local storage: http://diveintohtml5.info/storage.html
Similar to the cookie method, but on the first view have javascript store a key=value pair in local storage, and check against that each time the page loads. Something along these lines:
(function () {
window.onload = function () {
if (localStorage.getItem("SeenBefore")) {
// Not first time viewed
} else {
localStorage.setItem("SeenBefore", true);
// First view
}
}
}())
Another option is, on the serverside, you could set a session variable the first time the page is viewed, then check agianst that each time a user sends a request for the page. This could also be achieved using cookies.

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.

changing window.location without triggering refresh

I have an AJAX form that submits GET requests. Because these are all GET requests these should be easily bookmark-able. Preferably I'd make my Ajax request, update the screen and then update window.location.href to be the URL for the new page.
Unfortunately this reloads the page. Is there any way I can get around this? Basically I'd like the URL bar to be a permalink bar, but it needs to be able to change to keep up with the state of the page.
window.location.hash is no good because that doesn't get sent to the server.
window.history.replaceState( {} , title, new_URL );
This will update the current page URL with a new one without refreshing.
Arguments:
Data object (must be one that could be serialized to text)
The new title of the changed window URL
The URL to change to (without refreshing)
The you could use the window.onpopstate = function(event){...} to listen to events when a user goes back or forward in the browser history and change things however you wish.
The hash is the way to go. Because, as you point out, changes to the hash don't get sent to the server, you have to send an async request to the server as well as updating the hash.
As a simple example, if your URL is http://server.com/page?id=4, when the user triggers the action you send an AJAX request for http://server.com/page?id=4, and set the page URL to http://server.com/page#id=4.
Furthermore, you have to have something to restore the state if the user reloads. This would usually be done by reading the hash value client-side and sending an async request to the server based on the state represented by the hash value.
if you want to do which works in current browser, you can't change window.location.href without reloading the page
your only option is to to change window.location.hash.
you can do that each time you make an ajax call. if you're using jquery, you can bind a function which update the hash each time an ajax call is made.
if you choose that you'll have to look for the hash on page load (actually don't know/think you can do that server side) and make that call to have your page on the state corresponding to the hash.
-- update
there is now an API which provide this functionality look for history.pushState, history.replaceState and window.onpopstate : https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries
it's not availlable everywhere yet ( http://caniuse.com/#feat=history ), there is a few polyfill that you can use for the moment that will use this API if it's available and fall back using the url hash
Consider this JavaScript library: https://github.com/browserstate/history.js
Use jquery. It can do ajax requests. You cant use window.location because that is made to change the url.

Categories

Resources