A cookie code that make the following - javascript

First, I would like to have an easy code that creates a cookie called "x" for example and another code to put in other html that creates a cookie called "y". Then, in another html file, some code that checks if there is a previous cookie and:
If there is a previous cookie called "x", redirect to for example x.com page.
If there is a previous cookie called "y", redirect to other page, for example y.com.
If there isn't a previous cookie, do nothing.
The final code is:
create the cookie username en:
<script type="text/javascript">
var cookieDate = new Date(2012, 5, 02)
document.cookie = "username=en;expires=" + cookieDate.toGMTString();
</script>
create the cookie username es:
<script type="text/javascript">
var cookieDate = new Date(2012, 5, 02)
document.cookie = "username=es;expires=" + cookieDate.toGMTString();
</script>
Read the cookie and go to x.com if it's with the cookie has the value en and go to y if has the value es (and do nothing if there isn't cookie):
<script type="text/javascript">
function get_cookie (username)
{
var results = document.cookie.match(username + '=(.*?)(;|$)');
if (results[1] == "en")
location.replace("http://x.com");
if (results[1] == "es")
location.replace("http://y.com");
else
return null;
}
get_cookie('username');
</script>

It appears that your code defines a redirect function, but i don't see where you call the redirect function.
setting the cookie should look like this:
<script type="text/javascript">
var cookieDate = new Date(2012, 5, 02)
document.cookie = "username=en;expires=" + cookieDate.toGMTString();
</script>
Retrieve the cookie values like so:
<script type="text/javascript">
function get_cookie (username)
{
var results = document.cookie.match(username + '=(.*?)(;|$)');
if (results[1] == "en")
location.replace("http://x.com");
if (results[1] == "es")
location.replace("http://y.com");
else
return null;
}
get_cookie('username');
</script>

Related

Loop on back button after re-direction with querystring

The problem:
I need to start with a URL with a query string containing a URL of a second page - http://www.firstURL.com/?http://www.secondURL.com. On the target page of the first URL, the query string is parsed to extract the second URL and the browser is re-directed to the second URL. This is done on $(document).ready so that it's automatic. This all works fine, but of course falls in a hole if the user hits the back button on the second URL. Here's the basic code:
$(document).ready(function() {
var s = location.search;
if(s != '') {
var split = s.split('?');
var loc = split[1].replace('?', '');
location.href = '' + loc + '';
} else {
//do something else on the target page..
}
});
I've tried creating a conditional case where, if the referrer is the 2nd URL (loc in the code above), the re-direction doesn't execute, but it seems that in the case of a re-direction, the back button doesn't return the referrer.
I have to do all this client side - I have no access to the server.
Is there some way to prevent the re-direction triggering on a back button click? Thanks.
Once you hit the second page, set a cookie in your browser indicating that the second page has been visited.
In the first page, before doing the redirection always check whether the cookie is not present.
Instructions on setting a cookie:
<script type="text/javascript">
document.cookie="secondpagevisited=43yj0u3jt;path=/"; //execute this line in the head of second page.
</script>
In first page, check for cookie presence:
<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
/*do redirection here*/
}
</script>
EDIT: Assuming you control only the first page and not the second page, try this:
<script type="text/javascript">
if(document.cookie.indexOf("secondpagevisited=43yj0u3jt")==-1){
document.cookie="secondpagevisited=43yj0u3jt;path=/";
/*do redirection here*/
}
</script>
I gave Ashish the point for putting me on the right track, but this is my solution which goes one step further:
var s = location.search;
if(s != '') {
var split = s.split('?');
var loc = split[1].replace('?', '');
if (document.cookie.indexOf('redirected=' + loc + '') == -1) {
document.cookie = 'redirected=' + loc + '';
location.href = '' + loc + '';
} else {
var url = location.href.replace('' + s + '', '');
document.cookie = 'redirected=; expires=Thu, 01 Jan 1970 00:00:00 GMT';
history.pushState(null, null, '' + url + '');
}
If the cookie is there, the re-direction doesn't occur, the cookie is removed (in case the user returns to the site that had the original link and clicks it again), and the URL is tidied up by removing the query string.
Thanks for the guidance.

How to make JS page redirect trigger before page load

I am using the following script to redirect visitors of a page to another page on first visit, however it loads the index.html page first, and then triggers the redirect. Can anyone point me in the direction of how I might trigger this script before the page loads?
<script type="text/javascript">
function redirect(){
var thecookie = readCookie('doRedirect');
if(!thecookie){window.location = '/coming-soon.html';
}}
function createCookie(name,value,days){if (days){
var date = new Date();date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";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;
}
window.onload = function(){redirect();createCookie('doRedirect','true','1');}
</script>
(the JS snippet used here was taken from Stack Overflow: JS to redirect to a splash page on first visit)
Thanks.
You don't need to wait while window is loaded:
<script type="text/javascript">
var thecookie = readCookie('doRedirect');
if(!thecookie) {
createCookie('doRedirect','true','1');
window.location = '/coming-soon.html';
};
function createCookie(name,value,days){
// do work
}
function readCookie(name){
// do work
}
</script>
Also Petr B. said right thing: server-side redirect is better in your case.
Try this How to Run a jQuery or JavaScript Before Page Start to Load.
Btw. if you want redirect without displaying page you must use php with cookies check.

Javascript - checking if cookie exists on page load isn't working for me

I have the follwing code :
<script type="text/javascript">
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(date.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
alert("this is your first time");
}
}
</script>
<script type="text/javascript">
window.onload = myfuncc;
</script>
As you can see the window.onload function, I am trying to check if a vistor had already been at the site once the page loads. I am using cookies to do so. Problem is, I can't see the messages I am supposed to. Anyone knows why?
You have to set the expire date using toUTCString() method.
You also have a date object that is not initialized, try this:
function myfuncc () {
if (document.cookie.indexOf("visited") >= 0) {
// They've been here before.
alert("hello again");
}
else {
var expiry = new Date();
expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes
document.cookie = "visited=yes; expires=" + expiry.toUTCString();
alert("this is your first time");
}
}
give this a try:
var testarr = ["knirpsel", "text", "visited=yes"].indexOf("visited");
alert ( testarr );
output is "-1" which means the string "visited=yes" won't be found by search term "visited"
http://jsfiddle.net/m5x3M/
and
What is the best way to get a cookie by name in JavaScript?

how to delete particular cookie from cookies using jQuery

This is code which shows URL and delete image for delete cookie. add and display function is working but how to delete ??
function backLinks(){
var pathname = window.location;
var patientName = document.getElementById("general:patientDetailName").value;
var cookieTimeVal = jQuery.cookie('PCC_Back_Button');
if( cookieTimeVal== null){
cookieTimeVal ="";
}
// for writing Cookie
var stringCookie = "<span class='backLinkText1'><img src='../images/deleteImg.png' alt='' class='backLinkDeleteButton' onClick='deleteBackLink()'/></span><a class='backLinkText' href=\""+pathname+"\"> Patient History For \""+patientName+"\"</a>"+cookieTimeVal;
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
// read Cookie and set in HTML
jQuery('#backButtonSpan').append(
jQuery('<div>').attr({style:'padding-top:-10px;' }).append(cookieTimeVal)
);
}
**
function deleteBackLink(val){
jQuery.cookie(val, null);
}
**
How can I create a delete function and what parameter will I pass to it?
got a correct answer ...
in this i will replace cookie and delete inner html
function backLinks(stringValueAndName, patientName, patientDOB){
var pathname = window.location;
var cookieTimeVal = jQuery.cookie('PCC_Back_Button');
if( cookieTimeVal== null){
cookieTimeVal ="";
}
var time = new Date();
var spanId = time.getTime();
// for wright in Cookie
var stringCookie = "<span id ="+spanId+"> <img src='../images/deleteImg.png' class='backLinkDeleteButton' onClick='deleteBackLink("+spanId+")'/><a class='backLinkText' href=\""+pathname+"\">"+stringValueAndName +patientName+' ('+patientDOB +')'+"\</a></span>"+cookieTimeVal;
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
// read Cookie and set in HTML
jQuery('#backButtonSpan').append(
jQuery('<div>').attr({style:'padding-top:-10px;' }).append(cookieTimeVal)
);
}
function deleteBackLink(val){
jQuery('#'+val).remove();
var stringCookie = jQuery('#backButtonSpan div').html();
jQuery.cookie('PCC_Back_Button', stringCookie , { expires: 1 });
}
To delete a cookie with jQuery, set the value to null:
jQuery.cookie("name", null);
So your function will work - just pass the cookie name as a parameter:
deleteBackLink("name");
It doesn't. A cookie is a cookie.
The closest it comes is the HTTP Only flag, which allows a cookie to be hidden from JavaScript(mean client side). (This provides a little defence against XSS cookie theft).
A cookie is a cookie. (Again, client side code can't touch an HTTP only cookie)

Tracking values using JavaScript

on page A
test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session"));
Response.Redirect("EnterSession.aspx?session=" + e.CommandArgument.ToString());
on page B
_gaq.push(['pageTrackerTime._trackEvent', 'category', 'action', document.location.href, roundleaveSiteEnd]);
when a user clicks a button on page A , he will be directed to page B and there I used document.location.href to track the current URL. now I would like to track as well session_name from page A using JavaScript.
how can I do this
the original code was like this
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT * FROM Tmyapp_Session;";
SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
test.Controls.Add(GetLabel(thisReader["session_id"].ToString(), thisReader["session_name"].ToString()));
string[] compare = secondResult.Split(';');
foreach (string word in compare)
{
if (word == thisReader["session_id"].ToString())
{
test.Controls.Add(GetButton(thisReader["session_id"].ToString(), "Join Session"));
I had to change the last code to
test.Controls.Add(GetButton(thisReader["session_name"].ToString(), "Join Session"));
session_id to session_name
because i want to url to have the value of the session_name
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
// include getCookie and setCookie functions here
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
var username = getCookie("username");
if (username != null) { // registered user
document.writeln("Welcome back " +
username + ".");
var visits = getCookie("visits");
document.writeln(" You have been here " +
visits + " time(s) before.");
setCookie("visits",parseInt(visits)+1);
}
else { // new user
var username = prompt("What is your name ?","");
if (username != null) {
setCookie("username",username);
setCookie("visits",1);
document.writeln("Thank you. Please reload this page.");
}
}
</SCRIPT>
</BODY>
</HTML>
Hope this will work !!!
Looks like you just need to get the session_name from the querystring. Check out this post here, it has a couple of nice solutions for doing that.
I see two ways of accomplishing what you want, you could add another querystring
/url.aspx?session_name=[session_name]&session_id=[session_id]
or in a session variable
session["session_id"] = session_id;

Categories

Resources