Skip to content
Advertisement

Javascript onbeforeunload to open window.open() popup

I am trying to write a onbeforeunload event that triggers a window.open(url) etc. I want it to be triggered if the user trys to leave the page or if they close their browser, but not when they click any of the buttons on the page. The buttons on the page post data to the same page via a javascript.

javascript:

window.onbeforeunload = doSync;

function doSync(){
   if(doSync == true){
       //do sync via popup
       window.open("http://mydomain.com/page.php?var=<?php=sync_var?>", "Synchronizing cluster....", "location=0,menubar=0,statusbar=1,width=10,height=10");
   }
   else {
     //somehow do nothing and allow user to leave

   }
}
-->
</script>

The buttons calls a javascript function that creates a form and submits it. In that javascript function I set the global variable of doSync = false. I’ll include the basic code of this function just to illustrate it.

function buttonPush(){
   var form = document.createElement('form');
   form.setAttribute('method' bla bla

   //before submit set dosync to false
   doSync = false;

   form.submit();
}

right now I am getting a Not Implemented error on the window.onbeforeunload = doSync; statement.

Any help would be appreciated.

Thanks,

Jim

Is there something wrong with my window.open? if i do a window.open('','','height=100,width=100');

it opens fine but this below does not.

window.open('https://mydomain.com/support/sync_cluster.php?sync_cluster=mycluster','Synchronizing...', 'toolbar=0,scrollbars=0,location=0,statusbar=1,menubar=0,resizable=0,width=100,height=100');

Advertisement

Answer

doSync is a function, not a boolean; just create a variable and set it appropriately:

var sync = true;
window.onbeforeunload = doSync;

function doSync() {
  if (sync == true) {
    //do sync via popup
    window.open("http://mydomain.com/page.php?var=<?php=sync_var?>", "Synchronizing cluster....", "location=0,menubar=0,statusbar=1,width=10,height=10");
  }
  else {
    //somehow do nothing and allow user to leave
    return;
  }
}
function buttonPush(){
   var form = document.createElement('form');
   // form.setAttribute('method' bla bla

   //before submit set dosync to false
   sync = false;

   form.submit();
}
Advertisement