demlasjr
demlasjr

Reputation: 121

Make popup opening after a while even if the user is navigating to other page

I need a bit of help with this javascript code.

I have this code:

jQuery(document).ready(function(){
    if (document.cookie.indexOf('visited=true') == -1) {
    var fifteenDays = 1000*60*60*24*1;
    var expires = new Date((new Date()).valueOf() + fifteenDays);
    document.cookie = "visited=true;expires=" + expires.toUTCString();
    window.setTimeout(
function() {
    jQuery.colorbox({href:"/popup.htm", open:true, iframe:false, innerWidth:600, innerHeight:490}); 
        },

30000 )}});   

It's supposed to open a popup after 30 seconds, one time per day. The issue is that the popup it's opening after 30 seconds on stay on a page. It's there any way to make it to open after 30 seconds even if the client navigate to other page ? So, if the user stay 15 seconds on a page and 15 on another, getting the popup.

Thank you in advance

Upvotes: 1

Views: 2702

Answers (3)

Robin Maben
Robin Maben

Reputation: 23044

Yes.

But it's not possible using document.cookie.

You would need to use server-side cookies or HTML local storage/session storage.

Something like, Response.SetCookie("Visited", true). I don't know what you're using as back end.

Upvotes: 1

chrisfrancis27
chrisfrancis27

Reputation: 4536

The fundamental issue to overcome here is passing the 'state' between pages. Since you're already using cookies in your example, we'll work with that. You need to set a session cookie with the time the user has been on the site (initially 0). You'd then need to 'poll' the cookie once every so often (every 5 seconds maybe) to update the total time on site count, and read it back. If it's 30 seconds or more, fire the popup.

So instead of using:

setTimeout(function() {
    // open alert box
}, 30000);

You'd do something like:

setTimeout(function() {
    // Increment 'time-on-site' cookie value by 5000
    // Then, if 'time-on-site' cookie value >= 30000, fire popup
}, 5000);

UPDATE Of course, this requires a lot more back-and-forth to the server, as you need to communicate the updated value every 5 seconds.

Upvotes: 1

Marcelo De Zen
Marcelo De Zen

Reputation: 9497

No way man. Once the page is unloaded you cannot do anything else. You need to use other resources on server (cookies, session, etc..) to check if the window is already displayed or not.

Upvotes: 1

Related Questions