JavaScript redirect back to refer page - javascript

I am trying to make a button OR direct redirect which redirect user to page where he come from.
For example: If someone access my website from bbc post and register. Upon register success page, There should be a button or redirect function which take user back to bbc post or whereever he comes from.
I tried following cookie method but not worked also read some posts on stackoverlow but still no luck!
function setCookie(name,val,days) {
// DATE OBJECT
var date = new Date();
// NUMBER OF MILLISECONDS IN A DAY
var milliseconds = 86400000;
// MULTIPLY, THEN ADD TO CURRENT TIME
date.setTime(date.getTime() + (days * milliseconds));
// SET EXPIRATION VARIABLE
var expires = '; expires=' + date.toGMTString();
// CONCATENATE TO CREATE COOKIE
document.cookie = name + '=' + val + expires + '; path=/';
}
window.onload = function(){
if(document.referrer != ''){
// DESTROY ANY PREVIOUS DUPLICATE COOKIE
setCookie('referrer','',-1);
// CREATE COOKIE ON REGISTRATION PAGE
setCookie('referrer',document.referrer,1);
}
}
Can someone give any solution for this?

You can use the following and it should be useable in used even if the tab is opened in a new window.
if(document.referrer != ''){
// DESTROY ANY PREVIOUS DUPLICATE COOKIE
setCookie('referrer','',-1);
// CREATE COOKIE ON REGISTRATION PAGE
setCookie('referrer',document.referrer,1);
document.location.replace(document.referrer);
//replaces current url with new one eg. the (current) url is removed from history
//or
document.location.href = document.referrer;
//(current) url is in history/can use back button to go to previous page
}

Related

Javascript cookie value is lost after loading another page

I have a page with a hidden form where a value is echoed by php.
With javascript/jQuery I pick up the value and store it in a cookie. The user is redirected to an external page, then is redirected back to my site on a different page. On this page the cookie value is "0" (the value is lost).
Update: The last page is in a directory above the page where the cookie is set. I set the "path" on the cookie but it still doesn't work.
So - first I do the redirect (by submitting a form) , then I set the cookie:
function sendPostRequest(){
var $ = jQuery;
document.myform.submit(); //submitting the form
var now = new Date();
var time = now.getTime();
time += 144000 * 1000;
now.setTime(time);
document.cookie =
'member_id=' + $('#member_input').val() + //getting the value, setting the cookie
'; expires=' + now.toUTCString() +
'; path=http://domain-name/the-last-page/';
console.log(document.cookie); //the cookie is set
alert($('#member_input').val());
}
The cookie is set as it should after the redirect.
When the user comes back from the external page to the new page , it shows member_id=0 . So the value is lost.
I suspect something is wrong with the "path". I have tried path=/before. The initial page has a path like: http://domain-name/directory/the-first-page/ .
Update 2:
Another info that may be relevant is that the intial page is not SSL-encrypted, but the external page is SSL-encrypted, and the final page isn't.
var d = new Date();
var days=5;
d.setTime(d.getTime() + (days*24*60*60*1000));
var expires = ""+d.toUTCString();
document.cookie =
'member_id=' + $('#member_input').val() + //getting the value, setting the cookie
'; expires=' + expires +
'; path=/';
use date to set the expiry of the cookie and use this formula to set number of day for the expiry

Check if this domain is already open in the browser

I am setting a welcome message for my website that should be shown at the first time that users enter the website. So I display a specific element for some seconds when first page loads. The problem is each time that users go to homepage of the site would see the welcome message.
Is it a way that I check if this is the first time that user opens homepage?
I have no server-side code and every thing I have is javascript
You can set a browser cookie when the site is visited for the first time. Read the cookie. If cookie is available it means site is already visited. If cookie is not there it means site is visited for the first time and you have to display your welcome message.
javascript
window.onload = function() {
var visit=GetCookie("COOKIE1");
if (visit==null){ //show your custom element on first visit
alert("Welcome new user");
}
var expire = new Date();
expire = new Date(expire.getTime()+7776000000);
document.cookie = "COOKIE1=here; expires="+expire;
};
for further reference also see: http://www.htmlgoodies.com/legacy/beyond/javascript/cookiecountexplanation.html
jQuery
<script type="text/javascript">
$(document).ready(function() {
// check cookie
var visited = $.cookie("visited")
if (visited == null) { //first visit
$('.custom_element').show(); //show your custom element on first visit
alert("Welcome new user");
$.cookie('visited', 'yes');
}
// set cookie
$.cookie('visited', 'yes', { expires: 1, path: '/' });
});
</script>

How to detect if user has open more than one window or tab on the same session?

I would like to detect if user has open more than one window or tab on the same session and if he did it - I would like to print an special information on screen.
This limte should oblige only in one special URL, so if user has open two tabs/windows with urls: http://page.com/limite.htm - I would like to print special information. When user has open two windows/tabs with urls: http://page.com/limite.htm and http://page.com/index.htm - everything is OK and I wouldn't show any informations.
Is it possible?
Thanks.
I think the best way to do it is with localStorage. http://www.gwtproject.org/doc/latest/DevGuideHtml5Storage.html
From the link, about localStorage:
Availability to other Windows/tabs: Shared across every window and tab of one browser running same web app
So, you could set an entry when the tab/window is open, and change it when it's closed. When another tab/window is open, you first check this entry value.
Obviously you need to be careful: browser crashes, for example, might not trigger the "on close" part, so the user wouldn't be able to open a new tab, even with none open (localStorage persists!). If you have server sessions, you can ask the user to login again (or run your auth process again), and reset this value. You can also try to use a sessionStorage entry to keep track of this kind of problem. From the link, about sessionStorage:
Persistence: Survives only as long as its originating window or tab.
Also, there is something called "Cross window messaging", that allow you communicate between tabs, but check if it's supported on the browsers you want to support.
http://ajaxian.com/archives/cross-window-messaging-with-html-5-postmessage
I have done something very similar today. I hope this helps.
// helper function to set cookies
function setCookie(cname, cvalue, seconds) {
var d = new Date();
d.setTime(d.getTime() + (seconds * 1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// helper function to get a cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
// Do not allow multiple call center tabs
if (~window.location.hash.indexOf('#admin/callcenter')) {
$(window).on('beforeunload onbeforeunload', function(){
document.cookie = 'ic_window_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
});
function validateCallCenterTab() {
var win_id_cookie_duration = 10; // in seconds
if (!window.name) {
window.name = Math.random().toString();
}
if (!getCookie('ic_window_id') || window.name === getCookie('ic_window_id')) {
// This means they are using just one tab. Set/clobber the cookie to prolong the tab's validity.
setCookie('ic_window_id', window.name, win_id_cookie_duration);
} else if (getCookie('ic_window_id') !== window.name) {
// this means another browser tab is open, alert them to close the tabs until there is only one remaining
var message = 'You cannot have this website open in multiple tabs. ' +
'Please close them until there is only one remaining. Thanks!';
$('html').html(message);
clearInterval(callCenterInterval);
throw 'Multiple call center tabs error. Program terminating.';
}
}
callCenterInterval = setInterval(validateCallCenterTab, 3000);
}
LocalStorage won't work across protocols - so if the user has your site open in one tab using http, and another tab using https, both those tabs will see separate localStorage objects. Cookies don't have the same issue (they have other issues, e.g. inflating the size of every http request back to your website)
The sample code below maintains a map where the key is a unique browser tab identifier and the value is a timestamp indicating when that tab last confirmed it was still open. The map is stored in a cookie. Its not a perfect approach - each tab updates itself every 3 seconds rather than instantly, and there are race conditions (multiple tabs updating the same cookie) but depending what you're after this may do the trick.
If you ran this code on just a specific page you'd (more or less) know when that page was open more than once in the same browser. Or run it on every page of your website and know when your website was open in multiple tabs.
Cookie reading/writing code is omitted for brevity (but taken from https://stackoverflow.com/a/24103596/4486628), and the encoding of the data in the cookie is done with json for simplicity, but you get the idea.
If you run this code and watch the cookies using FireBug's cookie tab you can see the cookie updating as tabs are opened and closed. Actually doing something like alerting the user when multiple tabs are open is left as an exercise for the reader.
var timePeriod = 3000; // 3 seconds
function tabHandler() {
// ensure the current window has an identifier set
if (!window.name.match(/^MySite[0-9]{3}/)) {
window.name = 'MySite' + Math.round(Math.random() * 1000);
}
// read in the state of all the tabs
var tabCookie = readCookie('tabs') || null;
var tabs = JSON.parse(tabCookie) || {};
// update the timestamp for the current tab
var now = (new Date()).getTime();
tabs[window.name] = now;
// remove tab details that haven't had their timestamp updated
var tooOld = timePeriod * 2;
for (var tabKey in tabs) {
if ((now - tabs[tabKey]) > tooOld) {
delete tabs[tabKey];
}
}
// write back the current state of tabs
createCookie('tabs', JSON.stringify(tabs), 1);
setTimeout(tabHandler, timePeriod);
}
setTimeout(tabHandler, timePeriod);

show pop up only once throughout one navigation of the site

I have a website created using laravel. I want the user to be able to see a popup the first time he comes to my site.
By first time I mean- the user comes to any page on my site(this is first time), visits some of the linked pages on site(now, these page visits are not first time), opens facebook in the same tab(thus leaving my site) and then again opens my site in the same tab(this is first time again).
The basic reason behind one time popping up is not to bother the user again and again while he is navigating the site. But, once he leaves and comes back again, then I want to treat it like a new visit(and show the pop up again).
I know I can do popup thing with setTimeout() in jQuery. But how to do it just once? Please note that, the pop can appear on any page(if its first page of the current visit), not only on the home page.
you could use document.referrer, and check if the previous page is one of your domain. But not all visitors/browsers will return this value for security reasons.
So this is unreliable.
Use a plugin like jQuery Cookie, then simply do:
if(!$.cookie("popup"))
{
your_popup_function();
$.cookie("popup",true);
}
Edit: since you edited your question regarding your definition of "first time visit", I'd advise the approach Walter Brand suggested, using the referrer. Taken from this post:
document.referrer.indexOf(location.protocol + "//" + location.host) === 0;
Solution without using plugins:
var adCookie = document.cookie.indexOf('ad_displayed')
if (adCookie != -1) {
your_popup_function();
document.cookie = "ad_displayed=1";
}
This is the idea, of course you can set expiry date on the cookie. Read more here
Hi i did this solution while solving the client requirement "to show pop-up only once throughout navigating to different pages of the site" and it works good for me.
I did it using cookie and setting the cookie value to the cookie creation time than i make the difference of the cookie value with current time using javascript setInterval function and compare the difference with the time on which i want to show the pop-up and it's work.
$(document).ready(function()
{
var myVar="";
function getCookie(name)
{
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
function callagain()
{
if(!getCookie("magazine"))
{
var c1= new Date();
var c2=c1.getTime();
document.cookie="magazine="+c2;
}
var cvalue= getCookie("magazine");
var cvalue2=parseInt(cvalue);
myVar=setInterval(function(){ call22(cvalue2);},1000);
}
function call22(abcd)
{
var curdate = new Date();
var curtime = curdate.getTime();
var curtime2=parseInt(curtime);
var result=curtime2 - abcd;
if( (result >30000) && (result < 31000) )
{
alert(“POP UP ONCE THROUGHOUT THE SITE”);
clearInterval(myVar);
}
}
callagain();
});

Bookmarklet for set and read cookies

I need (for practice) to set a cookie via bookmarklet in website X, and read him with another bookmarklet from website Y.
For example, set a cookie named "user" with value of "Guy" in Google, and read this from YouTube.
I managed to set the cookie, but can't think of any idea how to read him from website b.
Thanks!
You need two bookmarklets, a getter and a setter.
You go to site X and use the getter bookmarklet to read the cookie and let the user copy it to his clipboard.
Then you go to site Y and use the setter. The setter will prompt the user for the bookmarklet and the user will then paste it into the prompt. The code will then set the cookie accordingly.
You can of course combine these two bookmarklets into a single getter/setter. The prompt will contain the current cookie for the page. The user can then choose to either copy the cookie and cancel (using it as a getter) or choose to to alter the cookie and click "OK" (using it as a setter).
I was looking for a way to share cookies of a specific website with a friend (reading them in my browser via bookmarklet and my friend setting them on his browser also via bookmarklet). Not quite what you asked for, but searching brought me here. This is my approach:
First there is a bookmarklet for exporting cookies. It will remove unnecessary white-spaces and encode your data in a base64 string for safe transport:
javascript:(
function(){
prompt("GET cookies encoded in base64", btoa(document.cookie.replace(/\s/ig, "")));
}
)
();
Then there is a second bookmarklet for importing all cookies encoded in the string. You can also set an optional lifetime here (thanks to https://www.quirksmode.org/js/cookies.html):
javascript:(
function(){
var inputstring = prompt("SET cookies decoded from base64");
var inputclean = atob(inputstring).replace(/\s/ig, "");
if (confirm("These cookies will be imported:\n\n" + inputclean.replace(/;/ig, "; "))) {
var days = prompt("Cookie lifetime in full days", "365");
var cookiearray = inputclean.split(";");
cookiearray.forEach(function(entry) {
var expires = "";
var split = entry.split("=");
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = split[0] + "=" + (split[1] || "") + expires + "; path=/";
});
}
}
)
();
Do not forget you have to run those on a specific website or tab. It does NOT export the entire collection of the cookies your browser is storing.
According to this StackOverflow, how to get cookies from a different domain with php and javascript you can't get cookies from another domain UNLESS you have access to it, as it would be a huge security flaw.

Categories