javascriptopera-mobile

How can I prevent the back arrow from closing a popup window in Opera Mobile 12?


My application has a popup window that our Android tablets running Opera Mobile 12 (the only mobile browser with proxy support and the last "real" Opera browser) render as a fullscreen window. That's fine, but the problem that arises is any errant tap of the back arrow immediately closes the window they are working in, since Opera doesn't support the beforeunload event, frustrating users when they accidentally tap near the bottom of the screen and hit the back arrow instead.

How can I prevent the back arrow from shutting the window without warning in Opera Mobile 12?


Solution

  • I solved the problem by taking advantage of the new History API:

    // snippet goes in the setup/DOMContentLoaded phase    
    if (typeof window.onbeforeunload !== "undefined") {
        // [standard warnings and whatnot here for non-Opera users]
    } else {
        // [optionally include checks for history support, if targeting multiple browsers]
    
        // force Opera forward whenever a history state is popped
        window.addEventListener("popstate", function(e) {
            history.forward();
        });
    
        // Create a new history state as soon as the popup window loads
        history.pushState(null, "Page Title Here");
    }
    

    This works by creating a new entry in the navigation history as soon as the page loads, then forcing the browser forward every time that state is popped off the stack (ie, the user hits the back arrow).

    You can easily modify this to display the same warnings that are assigned to window.onbeforeunload and close the popup if the user so desires, instead of completely disabling the close-by-back-button functionality.