通过window.open打开一个新页面,在新的页面里嵌入iframe。
路由:
<Router history={history}>
<Switch>
<Route path="/Demo" component={Demo} />
<Route path="/iframeDemo/:id" component={IframeDemo} />
</Switch>
</Router>
Demo.jsx
import React from 'react';
class Template extends React.Component {
constructor(props) {
super(props);
this.windowOpened = null;
}
receiveMessageFromIframe(event) {
console.log('receiveMessageFromIFrame...', event.data);
if (typeof event.data === 'string') {
console.log('receiveMessageFromIFrame...', event.data);
}
}
render() {
return (
<div className={styles.container}>
<span
onClick={() => {
this.windowOpened = window.open(
'/#/iframeDemo/id123456',
'newWindow',
'menubar=0,scrollbars=1, width=500,height=500, resizable=1,status=1,titlebar=0,toolbar=0,location=1',
);
this.windowOpened.addEventListener('message', this.receiveMessageFromIframe, false);
}}
>
点击打开新窗口
</span>
</div>
);
}
}
Template.propTypes = {
};
export default Template;
iframeDemo.jsx
import React from 'react';
class Template extends React.Component {
render() {
const { id } = this.props.match.params;
return (
<div className={styles.container}>
<iframe
id="myframe"
style={{ width: '100%', height: '100%' }}
title="iframe-demo"
width="100%"
height="100%"
srcDoc={`
<button id='send-btn'>发送信息</button>
<img
style="width: 100%;height:100%;"
id="myImg"
/>
<script>
var img = document.getElementById('myImg');
// 如果遇到执行canvas.toDataURL执行失败,可以设置img.crossOrigin
// 设置img.crossOrigin有个前提条件,就是服务器必须允许跨域访问。不然
//无法转换
// img.crossOrigin = "Anonymous";
img.onload = function(){
console.log('img...on...load=======', window.parent)
console.log('img...on...load2=======', window)
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
var dataURL = canvas.toDataURL("image/png");
canvas = null;
console.log('img..base64..', dataURL)
}
img.src = 'http://www.xxx${id}.png'
let sendBtn = document.getElementById('send-btn');
sendBtn.addEventListener('click', function (e) {
window.parent.postMessage('这是iframe发送的信息', '*');
}, false);
</script>`
}
>
<p>浏览器不支持iframe</p>
</iframe>
</div>
);
}
}
Template.propTypes = {
};
export default Template;