Skip to content

isDom判断逻辑兼容iframe的node #639

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/Dom/findDOMNode.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import React from 'react';

export function isDOM(node: any): node is HTMLElement | SVGElement {
const win = (node?.ownerDocument?.defaultView || window) as typeof win;

// https://developer.mozilla.org/en-US/docs/Web/API/Element
// Since XULElement is also subclass of Element, we only need HTMLElement and SVGElement
return node instanceof HTMLElement || node instanceof SVGElement;
return node instanceof win.HTMLElement || node instanceof win.SVGElement;
}

/**
Expand Down
18 changes: 18 additions & 0 deletions tests/findDOMNode.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,24 @@ describe('findDOMNode', () => {
expect(true).toBeFalsy();
}
});

it('isDOM type in iframe', () => {
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const svg: any = iframe.contentWindow.document.createElementNS(
'http://www.w3.org/2000/svg',
'svg',
);

// debugger;
// This `getBoundingClientRect` is used for ts type check
if (isDOM(svg) && svg.getBoundingClientRect()) {
expect(true).toBeTruthy();
} else {
expect(true).toBeFalsy();
}
});

it('should return DOM node from ref.current', () => {
const TestComponent = React.forwardRef<HTMLDivElement>((_, ref) => {
return <div ref={ref}>test</div>;
Expand Down