devrelm / resize-observer

Other
98 stars 12 forks source link

fix: allow observing elements created in different window context #100

Closed devrelm closed 2 years ago

devrelm commented 2 years ago

Per conversation here: https://github.com/pelotoncycle/resize-observer/issues/98#issuecomment-969156160

99 didn't go far enough in fixing the issue presented in #98.

Though #99 does allow observing elements that exist in a different iframe, those elements must be attached to a document that is part of the same window context that the elements were created in.

It is possible, though, for an Element to be created in one frame/window and then attach it to a document in a different frame/window. In these cases, target.ownerDocument is updated to be the document that the element is attached to rather than the document that the element was originally created in. This makes it much more difficult to find out if it is an Element, since we can no longer assume that target.ownerDocument.defaultView.Element is the same Element class that the target was instantiated with.

We could technically loop through window.frames (or, window itself), but that gets to be a bit involved and also has both performance and reliability implications. For instance, an error is thrown if we try to access window.frames[0].Element, if window.frames[0] is a cross-origin frame. I can't be certain that we'd catch all the possible errors there, so instead we'll just go with checking if target.nodeType === Node.ELEMENT_NODE and call it a day.