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>
Related
When I click to allow the cookie on the blog page, then it has its own path. After that, I go back to the index page it asks for a cookie again.
(But, if I click allow on the index page, the cookie could connect to every page.)
[enter image description here][1]
This happens when I click allow on the index page and blog page. (It has 2 cookies and the same name, but it would record in a different path)
[1]: https://i.stack.imgur.com/mjlI4.png
acceptBtn = cookieBox.querySelector(".consent_buttons button");
acceptBtn.onclick = ()=>{
document.cookie = "Geek-Cookies=GEEKGENTH; max-age"+60*60*24*30;
if(document.cookie) { //if the above cookie had set
cookieBox.classList.add("hide");
}else {
alert("Cookie can't be set!");
}
}
let checkCookie = document.cookie.indexOf("Geek-Cookies=GEEKGENTH");
checkCookie != -1 ? cookieBox.classList.add("hide"): cookieBox.classList.remove("hide");```
Thank you in advance,
I'm trying to find a way in javascript to check which URL is loaded, then have a popup notifying the user to update their old bookmarket and have it redirect to the new location in a few seconds.
For example, the url maybe Http:\abc\myappage and I want to check if they are on the http:\abc site which if they are, the notification pops up and redirects them.
Currently I have a simple redirect to take them to the new site, but I never considered anyone that has an old bookmark which would never get updated if you don't inform them about the change.
Thanks.
You can access the current url from within JavaScript with window.location.
Using window.location you can access the current domain and path, then by setting window.location.href = 'your new site' after a few seconds or after some user interaction will cause the browser to navigate to the supplied url.
if(window.location.host === 'abc'){
alert('This url is no longer valid.');
window.location.href = 'http://abc/myappage
}
You can use window.location to get some information regarding the current url:
window.location.origin in the console on this current page, prints:
"http://stackoverflow.com"
Then you could run some JS logic to check against your other url and use alert() to crete the pop up.
working JSBIN: https://jsbin.com/gijola/edit?js,console
adding code:
function checker (url) {
var here = window.location.origin;
l(here);
if (here !== 'whatever you want to check') {
alert('please update your bookmark!!');
}
}
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);
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
}
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();
});