如何跨站点维护全局变量..

时间:2014-10-18 08:58:11

标签: javascript jquery

我的动机:在逐渐增加时间之后调用函数说XYZ()。

first time after 3 secs, 
second time:6 secs
third time: 12secs

这应该发生在页面上..页面A,B,C 页面第一个弹出窗口然后他浏览页面B然后时间应该增加/加倍

我知道setInterval函数..但我很困惑如何使用它..

1)制作新的js并调用主文件

2)在所有页面中编写脚本。

2 个答案:

答案 0 :(得分:0)

//Following code may help you
//using cookie we are handing navigation count

function createCookie(name, value, days) {
    if (parseInt(days, 10)) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = name + "=" + escape(value) + expires + "; path=/";
}

// copied from http://lea.verou.me/2009/12/reading-cookies-the-regular-expression-way/
function readCookie(name) {
    name = name.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
    var regex = new RegExp('(?:^|;)\\s?' + name + '=(.*?)(?:;|$)', 'i'), match =     document.cookie.match(regex);
    return match && unescape(match[1]);
}

var navcountval;
if (!readCookie("navcount")) {
    navcountval = 1;
    createCookie("navcount", 1, 365);
} else {
    navcountval = readCookie("navcount");
    navcountval = parseInt(navcountval) + 1;
    createCookie("navcount", navcountval, 365);
}

// your code for of setTimeout based on pagenavcount * seconds like "navcountval * 3sec"

答案 1 :(得分:0)

您必须在每个网页中包含此javascript,这应该达到我认为您要实现的目标。此脚本每3秒将“timeTracker”cookie的值加倍

function updateInterval() {

    var pageCookies = document.cookie.split(';');
    var lastValueOfTimeTracker = 3;

    for(var i=0; i< pageCookies.length; i++) {

        var currentCookie = pageCookies[i].split(',');

        if(currentCookie[0].indexOf('timeTracker') != -1) {
            var temp = currentCookie[0].split('=');
            alert(temp[1]);
            lastValueOfTimeTracker = temp[1];
        }
    }

    document.cookie = 'timeTracker=' + (lastValueOfTimeTracker * 2);        
}