exit popup (нужна помощь в доработке)

kuzmit42

Постоялец
Регистрация
9 Янв 2013
Сообщения
132
Реакции
31
Начнем с того что не знаю JS
Есть скрипт, который спрашивает закрыть ли окно, и перекидывает в ифрейме по заданному url
Но он срабатывает только 1 раз. Т.е. Нажимаем закрыть окно - он спрашивает закрывать или нет. Если жмем остаться на странице то второй раз при закрытии он не срабатывает. А нужно чтобы он срабатывал до бесконечности - пока не нажмем покинуть страницу.
Код скрипта прилагаю. Помогите пожалуйста сделать чтобы он работал не один раз а бесконечно.
Код:
<script language="javascript">
function get_cookie(cookie_name) {var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );if(results) {return(unescape(results[2]))}else {return 0;}}
if(get_cookie("popapnum")<9) {
var x = get_cookie("popapnum");
var popapnum = ++x;
var cookie_date = new Date ( 2043, 01, 15 );

var exitsplashmessage = 'текст сообщения';
var exitsplashpage = 'http://blogperhour.blogeb.bolgov.e-autopay.com/';
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function () {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
function addClickEvent(a, i, func) {
    if (typeof a[i].onclick != 'function') {
        a[i].onclick = func;
    }
}
var theDiv = '<div id="ExitSplashDiv"  style="display:block; width:100%; height:100%; position:absolute; background:#FFFFFF; margin-top:0px; margin-left:0px;" align="center">';
theDiv = theDiv + '<iframe src="' + exitsplashpage + '" width="100%" height="100%" align="middle" frameborder="0"></iframe>';
theDiv = theDiv + '</div>';
theBody = document.body;
var PreventExitSplash = false;
function DisplayExitSplash() {
    if (PreventExitSplash == false) {
        window.scrollTo(0, 0);
        PreventExitSplash = true;
        divtag = document.createElement("div");
        divtag.setAttribute("id", "ExitSplashMainOuterLayer");
        divtag.style.position = "absolute";
        divtag.style.width = "100%";
        divtag.style.height = "100%";
        divtag.style.zIndex = "99";
        divtag.style.left = "0px";
        divtag.style.top = "0px";
        divtag.innerHTML = theDiv;
        theBody.innerHTML = "";
        theBody.topMargin = "0px";
        theBody.rightMargin = "0px";
        theBody.bottomMargin = "0px";
        theBody.leftMargin = "0px";
        theBody.style.overflow = "hidden";
        theBody.appendChild(divtag);
        return exitsplashmessage;
    }
}
var a = document.getElementsByTagName('A');
for (var i = 0; i < a.length; i++) {
    if (a[i].target !== '_blank') {
        addClickEvent(a, i, function () {
            PreventExitSplash = true;
        });
    } else {
        addClickEvent(a, i, function () {
            PreventExitSplash = false;
        });
    }
}
disablelinksfunc = function () {
    var a = document.getElementsByTagName('A');
    for (var i = 0; i < a.length; i++) {
        if (a[i].target !== '_blank') {
            addClickEvent(a, i, function () {
                PreventExitSplash = true;
            });
        } else {
            addClickEvent(a, i, function () {
                PreventExitSplash = false;
            });
        }
    }
}
addLoadEvent(disablelinksfunc);
disableformsfunc = function () {
    var f = document.getElementsByTagName('FORM');
    for (var i = 0; i < f.length; i++) {
        if (!f[i].onclick) {
            f[i].onclick = function () {
                PreventExitSplash = true;
            }
        } else if (!f[i].onsubmit) {
            f[i].onsubmit = function () {
                PreventExitSplash = true;
            }
        }
    }
}
addLoadEvent(disableformsfunc);
window.onbeforeunload = DisplayExitSplash;}
</script>
Есть еще один скрипт. Он работает до бесконечности, но там нет встраимого фрейма и нельзя задать страничку которую показывать если остаемся на сайте.
В общем нужно в первом скрипте запретить закрытие окна не 1 раз а бесконечно как в этом скрипте.
Код:
<script>
/*http://stackoverflow.com/questions/5587774/how-to-prevent-the-exit-popup-from-showing-when-clicking-input-buttons?rq=1*/
window.onload = function(){

    var allowUnload = true;

    window.onbeforeunload = function(e){
        //allowUnload will allow us to see if user recently clicked something if so we wont allow the beforeunload.
        if(allowUnload){
            //message to be returned to the popup box.
            var message = 'Are you sure you want to leave this page message',
                e = e||window.event;
            if(e)
                e.returnValue=message; // IE
            return message; // Safari
        }
    };
    // We need this to allow us to see if user has clicked anywhere if user has clicked we wont allow beforeunload to run.
    document.getElementsByTagName('body')[0].onclick = function(){
        allowUnload = false;
        //setTimeout so we can reset allowUnload incase user didn't leave the page but randomly clicked.
        setTimeout(function(){ allowUnload = true; },100);
    };
};
</script>
<input type="button" onclick="parent.location = '/4.html';" />
 
По первому выражению вместо там где функция function DisplayExitSplash(){...}
Вместо:
Код:
return exitsplashpage;
Вставляем:
Код:
  return exitsplashpage;
}else{
  return exitsplashmessage;
}
Тут при срабатывании window.onbeforeunload = DisplayExitSplash;
Функция меняет свою переменную с PreventExitSplash = fasle на true. И соответвенно при следующем вызове события она не вызывается.
Код также требует переход по клику на элементы 'a' и 'form', которые должны быть в html файле.
При переходе по ссылке событие window.onbeforeunload будет срабатывать каждый раз.
 
Последнее редактирование:
Назад
Сверху