It took me some time to figure out how I want to approach this. In the end I decided to add an option to ignore the Background Color (the one that’s usuall on the right-click) as there’s no option to reliably (and quickly) calculate the actual border of a selection. That’s only because a selection doesn’t have to be a simple rectangle but there’s no way to know that within a script.
I hope this solution is helpful for you ✌️