Close popup with escape button while popup active

I make prefab object as popup for exit confirmation in android device.
I call the prefab with escape (back button on android) and it’s succeed. But, how to close this popup again if escape (back button android) is pressed while this popup is active?
With this code, if popup is active and I press escape again, the popup will be stackep up.
This is my code to call the popup with escape (back button android) in unity. Thanks a lot for your help.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class Quit : MonoBehaviour
{
    // Start is called before the first frame update
    void Update()
    {
        Action action = () => {
            Application.Quit();
        };

        if (Input.GetKeyDown(KeyCode.Escape)) {
            Popup popup = UIController.Instance.CreatePopup();
            //Init popup with params (canvas, text, text, text, action)
            popup.Init(UIController.Instance.MainCanvas,
                "Are you sure want to exit?",
                "No",
                "Yes",
                action
                );
        };
    }
}

If you want escape to do different behaviour based on whether a popup is already active then you’ll need to change the contents of the if-statement to check for this.

if (Input.GetKeyDown(KeyCode.Escape)) {

    if (UIController.Instance.IsPopupActive())
    {
        UIController.Instance.ClosePopup();
    }
    else
    {
        Popup popup = UIController.Instance.CreatePopup();
        //Init popup with params (canvas, text, text, text, action)
         popup.Init(UIController.Instance.MainCanvas,
             "Are you sure want to exit?",
             "No",
             "Yes",
             action
             );
    }
}

There are two functions here you’ll need to implement within the UI controller (if you don’t already have something similar).

Let me know if you need further clarification!

The issue is because the keypress event does not trigger for non-printable characters (eg backspace or escape).

To solve the problem, you could use keydown instead:

function ESCclose(evt) {
if (evt.keyCode == 27) {
//window.close();
console.log(‘close the window…’)
}
}