You can add the attribute popover to the dialog element. This enables you to use the popover API, which has native support for detecting clicks outside. You can also use the popover API with any HTML element too!
popover
Try out the popover here!