简体   繁体   中英

Where do I put onWindowBeforeUnload?

I have a SAP UI5 application and I would like to show a box that appears when the user tries to navigate away from the screen through methods outside my application (clicking on links, manually changing URL, etc).

I see there is a onWindowBeforeUnload() method but I am not sure where I put this method or how it gets called. I tried including it in my controller that I want the functionality in but it does not get called when I navigate away. If there's any other function that can provide this behavior, that'll be fine too.

Here's what I did in my controller:

onWindowBeforeUnload: function() {
    alert("you sure?");
},

I see that this is a method of the component class but I thought this was created in the beginning; I am not too familiar with this concept.

There are a couple different ways of doing it:

in the body tag

<body onbeforeunload='alert("no!!")'>

in your js code:

<script>
    window.onbeforeunload = function() {
      alert('no!!');
    }
</script>

Make sure to use window.onbeforeunload and not onWindowBeforeUnload .

Also, make sure you put the code within tags in the rendered output of your page, or inside an included javascript file. Based on what your code looks like, it sounds like you are using a javascript library, which is why you are using functionName: function(){ //body } . You cannot use that method to override the window.onbeforeunload function, because you are trying to handle the function inside a sub-node of window. You have to use the top-level window node and handle the function there. And you can do that by putting this code directly inside <script> tags or the body tag.

I don't think you can override it directly from your controller. You'll either have to override it on the window object itself (as per @matt-spinks' answer above) or override it on your Component.js file (if you are using one).

Here's how to do it on the Component.js file:

sap.ui.define(["sap/ui/core/UIComponent"], function (UIComponent) {
    "use strict";
    return UIComponent.extend("company.main.Component", {
        // ...
        // ...

        /**
         * Fired before the window closes or moved to another URL
         */
        onWindowBeforeUnload: function(oEvent) {
            // your code
        },

        /**
         * Fired when the window is closed.
         */
        onWindowUnload: function(oEvent) {
            // your code
        }
    });
});

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