简体   繁体   中英

YII2 and javascript event “window.onbeforeunload”

I have to alert users before they change page on YII2 application (and I need to execute some other code befeore they leave) but javascript code I usually use on simple html/php pages, doesn't work in YII2.

This is the code in create.php under views:

$noback = <<< JS
window.onbeforeunload = closing;
var closing = function () {
        console.log("Message");
        window.alert("If you exit this page you will lose your data!");
        // other actions
}
JS;
$this->registerJs($noback, View::POS_READY);

If I put the code in _form.php it is the same.

There are a lot of restrictions on what is possible in an onbeforeunload handler. See MDN: onbeforeunload event handler .

On most modern browsers, you cannot spawn an alert from a beforeunload handler. You also cannot customize the message in the beforeunload handler.

At a basic level, you should define closing before assigning it to window.onbeforeunload . The variable may be hoisted here, but not the definition. I would recommend either changing closing to a function declaration, or definining it in the assignment operation.

window.onbeforeunload = closing;
function closing() {
  console.log("Message");
  return "If you exit this page you will lose your data!";
}

// OR

window.onbeforeunload = function() {
   console.log("Message");
   return "If you exit this page you will lose your data!";
}

You can execute other code in here, but in general trying to mimick or spoof browser-generated UIs will not work.

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