import React, { Component } from 'react';
export class Iframe extends Component {
constructor(props) {
super(props);
this.state = {
display: 'block',
height: 'auto'
}
this.offsetX = 0;
this.offsetY = 0;
}
componentDidMount() {
const iframe = document.getElementById(`a`);
let interCount = 0;
fetch(this.props.url).then((response) => {
return response.text();
}).then((data) => {
iframe.contentWindow.document.open("text/html", "replace");
iframe.contentWindow.document.write(data);
iframe.contentWindow.document.close();
this.inter = setInterval(() => {
const height = parseInt(iframe.style.height, 10);
const iframeClientHeight = iframe.contentWindow.document.documentElement.clientHeight;
if (height != iframeClientHeight) {
iframe.style.height = iframeClientHeight + 'px';
} else {
if (interCount > 5) {
interCount = 0;
clearInterval(this.inter);
}
}
interCount++;
}, 200);
})
}
handleClick = (event) => {
console.log('event=', event)
const iframe = event.target.parentNode.querySelector('iframe');
const iframeDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
const {x, y} = iframe.getBoundingClientRect();
console.log('x=',x,'y=',y)
const clickElement = iframeDoc.elementFromPoint(this.offsetX - x, this.offsetY - y);
const newEvent = iframeDoc.createEvent('HTMLEvents');
newEvent.initEvent('click', true, true);
clickElement && clickElement.dispatchEvent(newEvent);
}
handleMoveStart = (event) => {
console.log('event=', event)
this.offsetX = event.pageX || 0;
this.offsetY = event.pageY || 0;
}
render() {
return (
<div
onMouseMove={this.handleMoveStart}
onClick={this.handleClick}
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 2
}}
>
</div>
<iframe
id={`a`}
src={"about:blank"}
scrolling={"no"}
style={{
border: 'none',
width: 260,
position: 'absolute',
left: 0,
top: 0,
display: this.state.display,
height: this.state.height,
}}
/>
);
}
}
网友评论