Redirect only one time - javascript

I have a site (landing) that when a user enter automatically goes to another site (its a simple redirect using window.location in the index.html).
The problem is when the user click in the back button on the browser, because when the user goes back, come back to the landing redirect, so the user returns be redirected.
How I can make this redirection only one time per user?
I do not know if it's important but the site (landing) is another domain that the domain of the redirection.
Thank you.

Using the cookie solution. Something like this if I understood your needs correctly:
if (getCookie("first_visit") != "true") {
document.cookie = "first_visit=true";
location.href="NEW_URL";
}
//from http://www.w3schools.com/js/js_cookies.asp
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}

Related

how to delete a cookie if the browser crashes

I have a situation in my application where the users should are not allowed to open multiple instances of the application in a browser. So we are reading the cookies, if there is a session already opened we alerting the user that they are attempting to open multiple sessions.Some times if the browser crashes for some reason the browser is still having the old cookie and when the user is attempting to open the application again the browser is not allowing the user to login. User has to manually delete the cookie from the browser history. The business doesn't want that process.FYI I am using angularJS
Found the same question in other post but didn't find an answer I want here Can someone please help me out with this. Thanks in advance!
I came up with the following code. But when the application crashes the cookie is still sitting in the browser and not allowing the user to login at all. The only workaround for me now is to delete the cookie manually from the browser and login.
var duplicateApp = false;
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
window.onload = function(){
var MyAppCount=readCookie("MyApp");
if (MyAppCount > 0) {
duplicateApp = true;
alert("You are attempting to open multiple application sessions.\n\nPlease close any existing application from the web browser before restarting the application.");
var win = window.open("about:blank", "_self"); win.close();
}
else {
duplicateApp = false;
createCookie("MyApp", 1, 1);
window.onunload = function(){
if (duplicateApp == false) eraseCookie("MyApp");
};
}
};
Could you please suggest any changes I have to make to restrict the user to open only single instance of the application.
I would typically handle this on the login page by creating a new session and invalidating the old one when a user logs in again with the correct credentials.

Javascript Cookie Not Setting

I have an application that needs to pop a URL based on a Query String sent to it. Unfortunately, we can't insert any javascript into the application itself, but we can insert an iFrame that loads a page running javascript. There is a bug in the application where it loads the content in the iFrame twice within a couple seconds, which results in the URL popping twice.
To resolve this, I decided to set a cookie with an expiration. Before popping, I would check to see if the cookie exists, and if it does, prevent the pop from happening.
Unfortunately, my cookie is not being set. I've read a few threads about Javascript cookies trying to figure this out. The first thing I found is Chrome does not accept cookies from local files, so I set up an IIS server to host the page.
However, the cookie still is not being set. I read this page to make sure my code was correct, and as far as I can tell, it should be correct.
The code for my page is below. Any help would be greatly appreciated.
<html>
<head>
<script type="text/javascript">
var isPopped;
function myFunction() {
alert("Hello! I am an alert box!");
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function pop() {
var queryString = location.search.substring(1); //Get Query String from URL of iFrame source. The substring(1) strips off the ? and only takes the first substring. This can be modified to take more and the resulting string can be edited with Regular Expressions if more flexibility is required.
var urlToPop = "https://www.google.com/#" + queryString //Set URL to pop.
var recentVisitTrue=getCookie("visitRecent");
if (recentVisitTrue != "") {
isPopped = 1;
} else {
window.open(urlToPop,"_blank");
setCookie("visitRecent", "true");
}
}
function setCookie(cName,cValue) {
var date = new Date();
date.setTime(d.getTime() + 8000000);
var expires = "; expires=" + date.toGMTString();
document.cookie = cName + "=" + cValue + expires + ";path=/";
}
function getCookie(cName) {
var name = cName + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
</head>
<body onload="pop();">
v0.32
</body>
</html>
Thanks!

User Session becomes null on page change when using Parse Javascript SDK

I am making a website that uses the Javascript Parse SDK and calling Parse.User.current() only works some of the times causing my redirect to kick users back to the login page even though Parse.User.logOut() has not been called. I am using the User class and not having them login through Facebook.
Function to see if there is an active session. If there is, the page loads, otherwise the user should be redirected to the main page:
function checkUser(){
var currentUser = Parse.User.current();
if (currentUser) {
//the page loads
} else {
//redirect user to the login page
window.location = 'login-url';
}
}
The above code is called in the <head> tag of each page:
<script>checkUser()</script>
When the user logs in, I check to make sure Parse.User.current() is not null and then redirect them to the main page. The first time they are sent to the main page, the checkUser() function does not find a user, and they are sent back to the login page where my redirect() function (below) sends them back to the main page because Parse.User.current() is not null when it checks it. The second time they are sent to the main page, Parse.User.current() has a user, so they stay on this page.
To a user logging in, the above is not a problem, since after logging in, they end up on the right page, but the real issue arises when the user tries to navigate to a different page using the tabs name. When one of these is clicked, checkUser() on the new page does not find a user so the user is pushed back to the login page, where redirect() does find a user and sends them back to the main page where checkUser() finds a user as well, so they end up back on the main page again.
I do not know what the issue is, but I think it has something to do with initially changing the pages programatically because if I log in and then type the url of a different page into my address bar instead of clicking on a tab, the checkUser() finds a user and then I can use the tabs to switch pages without a problem. Additionally, it all occasionally works perfectly when I am using Chrome (this problem always occurs with Firefox) and then I log out and log back in and the same issue comes back.
My login code:
$("#login").submit(function(event){
event.preventDefault();
var name=$("#username").val();
var password=$("#password").val();
Parse.User.logIn(name, password, {
success: function(user){
if(Parse.User.current()){
window.location="main-page";
} else{
alert("no user");
}
}, error: function(user, error){
alert("login error:" + error.message);
}
});
});
Redirect called on the login page:
function redirect(){
var currentUser = Parse.User.current();
if (currentUser) {
//a user is found, so they are taken to the main page
window.location = 'main-page';
} else {
//the user has to log in
}
}
I was able to solve my problem by storing the userid in a cookie instead of relying on Parse.User.current(). I essentially just followed the steps outlined in http://www.w3schools.com/js/js_cookies.asp and since the login function I was using has a callback with the object, I could easily get the user's id when they log in using user.id.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var user = getCookie("userid");
if (user != "") {
//stay on page
} else {
window.location.href="login-url";
}
}
function removeCookie() {
setCookie("userid", "", -1); //setting the userid to an empty string
//and setting the expiration time to have passed
}
On the login and signup callback, I set the cookie and then redirect to the main page
setCookie('userid', user.id, 1);
window.location.href="main-page-url";
On all pages that require a user to be logged in, I check the cookie by calling checkCookie(); in the <head>. On the signin page, I also have a redirect so that if the user is signed in, they are redirected to the main page. This function is the same as checkCookie(), but I redirect when there is a user instead of when there is not one.
function checkCookie() {
var user = getCookie("userid");
if (user != "") {
window.location.href="main-page-url";
}
}
When the user logs out, I still call Parse.User.logOut(); but I also call removeCookie(); before redirecting to the log in screen.

Is it possible to automatically log in to link using Javascript

I want to link to a page and when the user clicks on the link his username and password are already there for him. However where i am linking too i don't control that pages code.
Is it possible to have my javascript execute there after the user clicks the link?
$("#link").click(function() {
alert( "Handler for .click() called." );
var username = getCookie("username");
var password = getCookie("password");
var usernameTextBox = document.getElementById("j_username");
var passwordTextBox = document.getElementById("j_password");
usernameTextBox.value = username;
passwordTextBox.value = password;
});
See my JSfiddle
You can't actually execute it from another page, you can however use the following.
The best way to do this is with a cookie, storing the username, and pointing to an encrypted file with an encrypted password. But you can store the encrypted password in a cookie too, as long as it's encrypted before putting it in the cookie.
I originally developed this for a function that will keep a user logged in to a page that redirected to a login whenever it is accessed, it will click the button and bring them to the page after the login page.
working example: Will need to be edited to fit exact elements on any page, and run on the page, probally through a property or permission gained through a download or web app etc.
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function stayLoggedIn() {
setCookie("logged_in","true",30);
setCookie("username", username,30);
setCookie("password",encryptedPassword,30);
return null;
}
window.onload {
var loggedIn = getCookie("logged_in");
if(loggedIn == true) {
var username = getCookie("username");
var password = getCookie("password");
var usernameTextBox = document.getElementById("username");
var passwordTextBox = document.getElementById("password");
//decrypt password here.
usernameTextBox.value = username;
passwordTextBox.value = password;
}
else {}
}
Explained:
first, we set a function to set a cookie and get one, I took these from here
then, I set the function stayLoggedIn() this sets the cookie with the value of "logged_in" to true, so when the user comes to the page, and window.onload runs it's block, the if statement is triggered, and the username and password fields are filled in.
Then, click(element) is called on the logginButton, this can click on php, or html buttons or submit forms etc. This simulates the button being clicked, and the user logging in.
Also: You need to call the function stayLoggedIn() after the link is clicked (like through a google or firefox extension)

onmouseover onmousemove executing so many times

var zoomPad = document.getElementsByClassName('zoomPad');
zoomPad[0].onmouseover = function(){
var action = 'image_zoom';
// Check if the activity is already logged
var checkCookie = getCookie('image_zoom');
if(checkCookie != '')
return false;
//Log activity of hovering image
$.ajax({
type: 'POST',
url: '/ajaxCall/user-activity-ajax.php',
data: {action:action},
success: function(response)
{
document.cookie = "image_zoom = " + action;
console.log(response);
}
});
} // end zoomPad
Hi,
I am trying to log a user event when he mouse over the image..but it should not be logged more than once on a signle page that's why i implemented cookie to stop executing ajax more than once.
But as soon i load the page and move my mouse over thei mage some times 5 , some time 9 calls are being fired to ajax . Same mechanism i applied to another drop down in a page but thats working fine.
THanks
Works well here : http://jsfiddle.net/7g5LX/
Maybe you should try this getCookie function (from http://www.w3schools.com/js/js_cookies.asp) :
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
Or call your cookie setter outside the ajax behavior (your set your cookie when your ajax call return 'success')
Okey,
One solution to this problem is to use jQuery more effectively by using "one" method to bind certain function to be run only once per element. This way, you can be certain that it won't re-run until it is necessary.
/*
Bind trackZoomPadActivity method to a mouseover, but do it using "one",
so it is binded to call mouseover only once
*/
$('.zoomPad').one("mouseover", trackZoomPadActivity);
The point when it should be re-run is when you detect through your ajax request that tracking has failed because of some unknown error with your server.
request.fail(function( jqXHR, textStatus ) {
// if request fails, we re-bind trackZoomPadActivity method, so
// person can try to mouseover again
$that.one("mouseover", trackZoomPadActivity);
});
Other than these points, here is a full code below which should work. The idea is to track event once per element & only re-attempt to redo the action if request has failed with the server:
Full code in JavaScript:
/*
Bind trackZoomPadActivity method to a mouseover, but do it using "one",
so it is binded to call mouseover only once
*/
$('.zoomPad').one("mouseover", trackZoomPadActivity);
/**
* Method for tracking zoomPad activity
*
*/
function trackZoomPadActivity() {
// action for this zoomPad
var action = 'image_zoom',
// referencing to self
$that = $(this);
// check if the activity is already logged
var checkCookie = readCookie(action);
// if cookie exists already -- return
if(checkCookie) {
return false;
}
// log activity of hovering image
var request = $.ajax({
type: 'POST',
url: '/ajaxCall/user-activity-ajax.php',
data: { action: action }
});
request.done(function(msg) {
// request is processed successfully, we can save the cookie!
document.cookie = 'image_zoom = ' + action;
});
request.fail(function( jqXHR, textStatus ) {
// if request fails, we re-bind trackZoomPadActivity method, so
// person can try to mouseover again
$that.one("mouseover", trackZoomPadActivity);
});
}
/**
* Method for reading cookie value
*
*/
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Example of HTML elements for testing:
<img src="http://placehold.it/64/64" class="zoomPad" />
<img src="http://placehold.it/64/64" class="zoomPad" />
Cheers.

Categories