show pop up only once throughout one navigation of the site - javascript

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();
});

Related

How to get string URL from multiple past pages JavaScript

I am very new to JavaScript. I am trying to make a web application, where a simple back button will go to a specific page I am looking for, one that has the word "search" in it. I don't know the exact URL, because the parameters within that URL change, and I need to keep it consistent to what the user wanted. But this one button should go back to that one page, regardless of the other links that were clicked.
For example:
If I clicked on
Home Page
Main Page
Page 1
Page 1.3
Back
I want the back to always take me to Main Page with the exact parameters it had before, not Home Page.
I tried the following:
The button itself
movieTableBodyElement.append('' + " << Back" + ''); // Building the HTML button, calls the goBackHelper() function
function goBackHelper()
{
// checks if the page directly behind is the Main Page with "search"
if(document.referrer.includes("search"))
{
// if its the main page, exit the function and end recursive call
window.history.go(-1);
}
else
{
// it is not the last page, so go to the past page and check again
window.history.go(-1);
goBackFunction();
}
}
But this takes me to the very first home page. I thought that document.referrer would get me the past URL, but it doesn't seem to be working for me. Is there a way to get the URL from past pages? So if I am on page 2, can I get all the URLs and search for Main Page? Any help is greatly appreciated!
I'm also new to Stack Overflow, so if there is any clarification please don't hesitate to let me know!
document.referrer is not the same as the actual URL in all situations.
Your best bet is to store the URLs in sessionStorage.
Add this snippet of code to your pages:
if (sessionStorage.getItem("locationHistory") !== null) {
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
} else {
var locationHistoryArray = [];
locationHistoryArray.push(window.location.href);
sessionStorage.setItem("locationHistory", JSON.stringify(locationHistoryArray));
}
And this is your goBackHelper() function :
function goBackHelper() {
var searchString = 'search'; //modify this
var locationHistoryArray = JSON.parse(sessionStorage.getItem("locationHistory"));
for (i = 0; i < locationHistoryArray.length; i++) {
if (locationHistoryArray[i].includes(searchString)) {
window.location.assign(locationHistoryArray[i]);
break;
}
}
}
Read about document.referrer here.

Determine if the browser already opened an URL

We use an internal system (with FF as default browser)
We need to avoid that the user open the same URL in different tabs.
As the tabs share the same PHP session we get a mess.
So actually I'm looking to the way to check programmatically if certain URL is already opened in one of the opened tabs.
Client side (JS) or server side (PHP).
We use now the FF extension "Duplicate Tabs Closer" that helps.
But I'd prefer to keep full control (give warning, choose for which URL it works).
You can write cookie after your page loaded in the first tab, check it on the server side and show the user warning instead of actual page content if this cookie is set and the second tab is opened. To handle the case when a user closes the only opened tab you can remove that cookie in onbeforeunload handler.
Working off of Oleksandr's answer, you can store a map of number of times a url is opened, in a cookie. When a page is opened, increment the number or set it to 0. When a page is closed, decrement it or delete it.
function incrementTabsOpen() {
let tabsOpen = readObjCookie('tabsOpen') || {};
if (tabsOpen[window.location.href]) tabsOpen[window.location.href]++;
else tabsOpen[window.location.href] = 0;
writeObjCookie('tabsOpen', tabsOpen);
}
function decrementTabsOpen() {
let tabsOpen = readObjCookie('tabsOpen') || {};
if (tabsOpen[window.location.href]) tabsOpen[window.location.href]--;
if (tabsOpen[window.location.href] === 0) delete tabsOpen[window.location.href];
writeObjCookie('tabsOpen', tabsOpen);
}
// https://stackoverflow.com/a/11344672/3783155
function readObjCookie(name) {
let result = document.cookie.match(new RegExp(name + '=([^;]+)'));
if (result) result = JSON.parse(result[1]);
return result;
}
function writeObjCookie(name, value) {
document.cookie = name + '=' + JSON.stringify(value);
}
and
window.addEventListener('load', function() {
incrementTabsOpen();
};
window.addEventListener('unload', function() {
decrementTabsOpen();
};

Issue with GTM and firing Facebook Pixel in a cross-domain setup

I am trying to track Facebook ad results using the Facebook Pixel during appropriate events (page views, lead generation, order form view, purchase). I can do all of this for GA using GTM with no problem, but on Facebook I only have partial success.
The main issue is I have a cross domain setup as shown below:
domain1.com/offer - landing page (FB Page View Pixel should fire)
domain1.com/ordergate - request email before showing order form page (FB Page View Pixel should fire)
crm.com/formsubmission - the actual form submits to my crm (FB Lead Pixel should fire)
crm.com/orderform - order form (FB order form view pixel should fire)
domain1.com/thankyou - the thank you page (FB order pixel should fire)
So my trigger on GTM to fire FB pixel was the "referrer" containing "facebook". However, because of the multi-step process, the referrer is lost by the time the order form or sale is completed.
I have since then learned I need to do the following:
User lands from facebook, write cookie with an appropriately short expiration time that stores this information on domaiin1.com.
When the user clicks a link and is redirected to crm.com, check if the user has the cookie, and if they do, add something like ?reffacebook=true to the redirect URL.
On crm.com, if the URL has ?reffacebook=true write the same cookie you wrote on (1) with an equally short expiration time.
UPDATE
So I have figured out step 2 using the following script on page view when the Facebook cookie is set:
function updateLinks(parameter, value)
{
var links = document.getElementsByTagName('a');
var includeDomains = self.location.host;
for (var i=0;i<links.length;i++)
{
if(links[i].href != "#" && links[i].href != "/" && links[i].href != "" && links[i].href != window.location) //Ignore links with empty src attribute, linking to site root, or anchor tags (#)
{
var updateLink = true;
if(links[i].href.toLowerCase().indexOf(includeDomains.toLowerCase()) != -1) //Domain of current link is included i the includeDomains array. Update Required...
{
updateLink = false;
}
if(!updateLink)
{
//Do nothing - link is internal
}
else
{
var queryStringComplete = "";
var paramCount = 0;
var linkParts = links[i].href.split("?");
if(linkParts.length > 1) // Has Query String Params
{
queryStringComplete = "?";
var fullQString = linkParts[1];
var paramArray = fullQString.split("&");
var found = false;
for (j=0;j<paramArray.length;j++)
{
var currentParameter = paramArray[j].split("=");
if(paramCount > 0)
queryStringComplete = queryStringComplete + "&";
if(currentParameter[0] == parameter) //Parameter exists in url, refresh value
{
queryStringComplete = queryStringComplete + parameter + "=" + value;
found = true;
}
else
{
queryStringComplete = queryStringComplete + paramArray[j]; //Not related parameter - re-include in url
}
paramCount++;
}
if(!found) //Add new param to end of query string
queryStringComplete = queryStringComplete + "&" + parameter + "=" + value;
}
else
{
queryStringComplete = "?" + parameter + "=" + value;
}
links[i].href = links[i].href.split("?")[0] + queryStringComplete;
}
}
else
{
//Do nothing
}
}
}
So with this code I can now properly attribute people with the facebook referral across domains...
...but I still have a problem with form submits.
So when the contact gets to step 4, it is a redirect from the form submission. It does not carry any cookie or query string, so neither of the FB pixels (order form view or order) is being fired.
I'm not sure how I would handle this. My first thought is to pass a hidden field into the form submission (say reffacebook=true). Then somehow expose that in the url in a form of a query string so that it can be detected by GTM.
This seems to be somewhat complicated though, as I would have to edit all my forms to have this variable, edit my CRM so it knows to receive it, and then edit the form landing page to expose that variable in the url.
Hey I hope that I understood what is this all about. Here you want to track traffic between cross domains right? I am not into any coding or anything like that to achieve such a tracking. Because I don't know any coding seriously (I apologies my self for not even trying to learn. I realize my self is that knowing Java script have a lot of benefits in advanced marketing). Ok Here is my point. If we want to track traffic between domains and retarget them later, wouldn't it be done by Facebook itself just by using the same pixel in both domains? This is what I used to believe in the case of multiple domains while doing Facebook ads. Here the important Thing is the audience should be the same from domain A to domain B (In your case it looks like yes the audience is same there for there is no issue for doing that I think). But not sure whether Facebook will track the traffic between domains successfully or not just by placing same FB Pixel in both domains.
Thank you.
#SalihKp, I think you have a point however the issue is that i believe facebook does cross domain with third party cookies which are not working optimally now adays
#David Avellan actually since the user returns to the landing domain for the thank you page, then the final conversion should work using 1st party cookies, but what you want in between might be an issue.
i am looking at now a case where they user lands on a.com and convert

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);

Update multiple windows via javascript

My site has a timeout set, so after 15 minutes of in-activity a login screen appears asking you to refresh your session.
This works great, but if you have more than one window open on the site it means one page will be refreshed with the login details but the other one will not.
So the question is this, is there a way to execute the following code on each window open at the site?
$jq('#loginbox').hide()
Thanks for any help. I should also state that the other windows will not be opened via JavaScript, the user could have just clicked open in new window / tab on a link
You cannot access windows you didn't open yourself with JS.
Each window should detect that it timed out and display a login dialog. If a user logs in in window A, then window B should be polling the server to detect if a session has been created, and restore itself in that case.
Before you switch to the refresh screen (popup?) you can simply do an ajax call to the server to see the last time the user refreshed - if the user is still legitimately logged in, just reset the timer to the proper time.
If the other window is not opened via JavaScript, you won't be able to access it programmatically. In other words, the original window is not going to be able to call JavaScript functions on the other window.
However, the windows can share cookies if they have the same domain (if they're on the same website). So one possibility would be to have the other window poll for updates to a session cookie, which the original window could write to. Once the session cookie obtained a particular value, the other window could detect this change and react as you saw fit.
Thanks to everyone who posted ideas, I went for the following solution, if anyone can enhance it and post code then I'll accept that as the answer:
$jq(function(){
$jq(window).bind('blur', function(){checkloginrefreshed();});
$jq(window).bind('focus', function(){checkloginrefreshed();});
$jq(document).bind('focusout', function(){checkloginrefreshed();});
$jq(document).bind('focusin', function(){checkloginrefreshed();});
});
function createCookie(name,value,hours) {
if (hours) {
var date = new Date();
date.setTime(date.getTime()+(hours*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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function checkloginrefreshed(){
if (parseInt(readCookie("loginset")) == 1){
eraseCookie("loginset");
$jq('#timeoutwarning').dialog("close");
$jq('#timeoutwarning').html(TIMEOUTLOGINFORM);
clearTimeout(timer);
clearTimeout(timerWarning);
setupTimers();
}
}

Categories