简体   繁体   中英

How to create one function on onLoad and onBeforeUnload event

I have the following code to call the onLoad and onBeforeUnload event:

<script type="text/javascript">
var startime = (new Date()).getTime();
window.onload = record_visit_ol; //ol - onload
window.onbeforeunload = record_visit_obul; //obul = onbeforeunload

function record_visit_ol() {
    var x = (window.ActiveXObject) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
    x.open("GET", "count_visit.php?t=" + (((new Date()).getTime() - startime) / 1000)+"&type=ol&url="+escape(window.location.href), false);
    x.send(null);
}

function record_visit_obul() {
    var x = (window.ActiveXObject) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
    x.open("GET", "count_visit.php?t=" + (((new Date()).getTime() - startime) / 1000)+"&type=obul&url="+escape(window.location.href), false);
    x.send(null);
}   

That works great. However, I have 2 function for 2 events. I have tried creating 1 function only but it fires both events during onLoad.

Here's the code that fires even the onBeforeUnload event on loading a page:

<script type="text/javascript">
var startime = (new Date()).getTime();
window.onload = record_visit('ol'); //ol - onload
window.onbeforeunload = record_visit('obul'); //obul = onbeforeunload

function record_visit(value) {
    var x = (window.ActiveXObject) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
    x.open("GET", "count_visit.php?t=" + (((new Date()).getTime() - startime) / 1000)+"&type="+value+"&url="+escape(window.location.href), false);
    x.send(null);
}

The problem is that you are calling the function in the 2nd set of code. You need to pass a function:

window.onload = function(){
    record_visit('ol'); //ol - onload
}

window.onbeforeunload = function(){
    record_visit('obul'); //obul = onbeforeunload
}

try this:

window.onload = function(){ record_visit('ol'); }
window.onbeforeunload = function(){ record_visit('obul'); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM