iframe.js 1.56 KB
import React, { Children, Component } from 'react';
import { createPortal } from 'react-dom';

export class IFrame extends Component {
	constructor(props) {
		super(props);
		this.setContentRef = (node) => {
			this.contentRef = node?.contentWindow?.document.body;
		};
	}

	bindIFrameMousemove(iframe) {
		iframe.contentWindow.addEventListener('mousemove', function (event) {
			var clRect = iframe.getBoundingClientRect();
			var evt = new CustomEvent('mousemove', { bubbles: true, cancelable: false });
			evt.clientX = event.clientX;
			evt.clientY = event.clientY;
			iframe.dispatchEvent(evt);
		});

		// iframe 안을 클릭했을 때, 해당 popup 창을 Click 한 것과 같은 효과를 준다.
		iframe.contentWindow.addEventListener('click', function (event) {
			var evt = new CustomEvent('click', { bubbles: true, cancelable: false });
			iframe.dispatchEvent(evt);
		});

		// dragging 하다가 mouse button을 up 하는 이벤트를 iframe 밖으로 전달.
		iframe.contentWindow.addEventListener('mouseup', function (event) {
			var clRect = iframe.getBoundingClientRect();
			var evt = new CustomEvent('mouseup', { bubbles: true, cancelable: false });
			evt.clientX = event.clientX;
			evt.clientY = event.clientY;
			iframe.dispatchEvent(evt);
		});
	}

	componentDidMount() {
		this.bindIFrameMousemove(document.getElementById('iFrame'));
	}

	render() {
		const { children, ...props } = this.props;
		return (
			<iframe id="iFrame" {...props} ref={this.setContentRef}>
				{this.contentRef && createPortal(Children.only(children), this.contentRef)}
			</iframe>
		);
	}
}