resize-observer-polyfill
resize-observer-polyfill copied to clipboard
Use different approach to check instanceof Element
trafficstars
The instanceof check does not always work correctly, especially when you work with elements created in a different contexts.
To demonstrate run this on some page:
const iframe = document.createElement('iframe')
document.body.append(iframe)
// Create element within iframe but append it to parent document
const iframeElement = iframe.contentDocument.createElement('div')
document.body.append(iframeElement)
// false because iframeElement was created in iframe context
console.log(iframeElement instanceof iframeElement.ownerDocument.defaultView.Element)
// true because element instance is checked against correct window context
console.log(iframeElement instanceof iframe.contentWindow.Element)
Suggested changes:
Stop using getWindow function and replace it with this one.
/**
* Returns boolean indicates whether given parameter is instance of Element
*
* @param {Object} maybeElement
* @returns {boolean}
*/
const isElement = maybeElement => {
return maybeElement && 'nodeType' in maybeElement && maybeElement.nodeType === Node.ELEMENT_NODE;
};
The same is true when using Proxies. It's enough to wrap an element in a Proxy to get this error.