Search code examples
javascriptoverlayuserscripts

Javascript detect elements in front of elements


How can one know if an element is in front of another element, if the overlaying element is transparent? The purpose for this is if you're artificially clicking a page element by its ID, and you're ensuring there's no overlay on top of the element that would make confirm the click as synthetic (as a normal user would have to click on the overlay).

Case 1: The overlay is a child of the clickable element To Detect it: Ensure there's no children of the clickable element that look unusual.

Case 2: The overlay has an absolute position and a higher z-index to overlay the clickable element To Detect it: No clue! Unless you iterate through the bounding rectangles and z-index of every element in the DOM or go through the entire DOM looking for particular style attributes. That is expensive.

So, given the number of ways an element can be made to overlay another element, how can a user script detect elements overlaying elements? I suspect a very verbose method of going through the entire DOM could be avoided.


Solution

  • It turns out there's two ways to do this, and by this I mean two ways to find out if any given element is the top most element regardless of opacity.

    Adapted from this blog post post and using their code (with some modifications) it's possible to see the top most element at any given mouse position. I modified their code to look for the computed style zIndex of any elements at a position. The downside to this approach is it's computationally costly in that you're looking at the positions of every element in the DOM more or less.

    This stack question about checking whether an element is really visible on screen received an answer that linked to a browser method document.elementFromPoint which when given some screen coordinates returns the top most element, regardless of opacity but in accordance with its display style. It appears as though that function is supported in at least Firefox and Chrome.

    In the end, there's two solutions to choose from, with the latter likely being the best solution in terms of reliability and cost.