Removing querystrings from the URL before page refresh - javascript

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.

Related

Stop a user from navigating past a signin form via the url

I have a website which contains a sign in page which should only allow the people knowing the info to pass the page, but if I type /nextpage.html in the url, it takes me past the sign in page. How can I prevent this? (I use javascript, not php)
If you use ASP.net backend for authentication. Then you do the following:
Upon successful sign in you have to set some session variable in
ASP.net
Then on every page load you need to make an ajax call to
check if the session variable is set, if it is, you show the content
that you wish to show to an authenticated user, otherwise, show them
a log in form.
you can put a variable which holds a user login status in session. if user is not logged in make it false or 0 after login make it 0 or true and put in session and check it always before page loads. and destroy session and make it false or 0 on logout.
So after a while of trying different methods, I came across javascript session- and localstorage. This is what helped me since variables stored in them can be used across multiple .js files.
Thanks for all the help!

Removing query params causing issue on page refresh

I have a URL with a query string attached to it. After the page loads, I am removing the query param using
history.replaceState("","",location.href.substring(0,location.href.indexOf("?")))
But when user hit refresh button its displaying error screen from my application since expected query param was not there in URL. I can use post action there but I would like to avoid query params with page refresh working fine. Is there any solution for this ?
If you're using a query parameter and then removing it, then the user hit's refresh and there is an error saying it's expecting a query parameter, then your code (and logic) is lacking.
My suggestion, if you want to avoid query parameter after the page initially loaded, is to save the parameter in a cookie or even a session if there is code-behind. Then if the user refreshes without the query parameter, check if the cookie exists, if the cookie exists, show them the page normally, if not, instruct them that they did not visit the URL through the correct channels.
However, like I mentioned, I think your logic here is flawed, because if the user wants to share your URL to the outside world, and you removed the key piece of information that makes the page load successfully, then you will have a lot of confused people on your hands
edit
You might want to investigate SEO friendly URL's to pass your query in to, so instead of: yoururl.com/?firstname=joe you can do yoururl.com/firstname/joe

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
}

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.

Categories

Resources