跨域修改iframe页面内容
postMessage
该方法需要使用 JSON.stringify 将对象转为字符串.
// React
function IframeProxy(props) {
handleLoad = (e) => {
e.target.contentWindow.postMessage(JSON.stringify({
iframe: `<iframe name="target" title="target" className="target" src="http://www.targetdomain.com/target.html" frameBorder="0" scrolling="no" style="width: 100%;height:100%"></iframe>`,
includeStyle: `
body {
background-color: yellow;
}
header {
display: none;
}
footer {
display: none;
}
`,
includeScript: `
window.addEventListener('load', function() {
alert(document.querySelector('body').innerHTML);
});
`,
importStyle: `http://www.mydomain.com/assets/css/import.css`,
importScript: `http://www.mydomain.com/assets/js/import.js`
}), 'https://www.target.com');
}
return <iframe name="proxy" title="proxy" className="proxy" width="100%" height="100%" onLoad={handleLoad} src={`http://www.targetdomain.com/proxy.html?origin=${window.location.protocol}//${window.location.host}`} frameBorder="0" scrolling="no"></iframe>;
}