2

I need a custom dialog box to appear when the user closes the browsers tab or window. I tried to write a component that wraps my app. This is how i tried:

import * as PropTypes from 'prop-types';
import * as React from 'react';
import WindowsCloseDialog from './desktop/windowsClose.dialog';

interface IProps
{
    onBeforeunload?: () => void;
}

interface IState
{}

const Dialog = (): JSX.Element => <WindowsCloseDialog />

class Beforeunload extends React.Component<IProps, IState>
{
    // Things to do before unloading/closing the tab
    doSomethingBeforeUnload = () =>
    {
        // Do something
    }

    // Setup the `beforeunload` event listener
    setupBeforeUnloadListener = () =>
    {
        window.addEventListener('beforeunload', (e: BeforeUnloadEvent) =>
        {
            e.preventDefault();
            return this.doSomethingBeforeUnload();
        });
    };

    componentDidMount = (): void =>
    {
        // Activate the event listener
        this.setupBeforeUnloadListener();
    }

    render()
    {
        const { children = null } = this.props;
        return children === null || children === undefined ? Dialog() : children;
    }
}

export default Beforeunload;

Then I wrapped my app:

const container =
      <Beforeunload onBeforeunload={ () => 'Test'}>
        <AppContainer>
          <Router history={ history }>
            <IndexRoutes/>
          </Router>
        </AppContainer>
      </ Beforeunload>

const ROOT = document.getElementById('root');

ReactDOM.render(container, ROOT);

Pages are loaded but when I close the window/tab no messages. I tried to replace Dialog() with string message, no success.

I tried the npm package idea form here without any success.

Anyone dose this before on some way, even if someone succeed for a page and cant help?!

thnx

Community
  • 1
  • 1
Wasyster
  • 2,279
  • 4
  • 26
  • 58

0 Answers0