【发布时间】:2020-07-21 08:32:22
【问题描述】:
我一直在寻找能够将 wordpress 页面嵌入到我的 React 应用程序中的方法。
问题
我可以简单地使用<iframe> 标记并手动插入高度,直到整个页面无需滚动即可显示。问题是我希望它是动态的,并且能够简单地获取 iframe 的高度并进行适当的设置。
Wordpress 在 AWS EC2 实例上运行,并通过我拥有的域进行访问。当使用 iframe-resizer-react 之类的库时,示例代码为
import React from 'react';
import IframeResizer from 'iframe-resizer-react';
interface ICustomIframeProps {
url: string; // https url of the wordpress page
}
const CustomIframe: React.FC<ICustomIframeProps> = ({ url }) => {
return (
<div>
<IframeResizer src={url} style={{ width: '1px', minWidth: '100%' }} />
</div>
);
};
export default CustomIframe;
我得到错误:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://my-wordpress-ec2.com') does not match the recipient window's origin ('http://localhost:3000')
已经尝试过的另一种解决方案是将原始 iframe 用作:
import React from 'react';
interface ICustomIframeProps {
url: string;
}
const CustomIframe: React.FC<ICustomIframeProps> = ({ url }) => {
const onIframeLoad = () => {
const iframe = document.getElementById('target') as HTMLIFrameElement;
iframe.style.height =
iframe.contentWindow!.document.body.offsetHeight + 'px';
};
return (
<div>
<iframe
title="Wordpress Iframe"
src={url}
id="target"
style={{ width: '100%' }}
onLoad={() => onIframeLoad()}
/>
</div>
);
};
export default CustomIframe;
但是,我明白了:
SecurityError: Blocked a frame with origin "http://localhost:3000" from accessing a cross-origin frame.
就我搜索的内容而言,this 建议如果我想获得iframe 中内容的高度,我需要向我的 Wordpress 实例添加代码。关于如何做到这一点的任何想法?
我正在寻找一种解决方案,我可以只在 Wordpress 上创建一个页面,并在使用 wordpress API 时检索我的页面,并在我的 react 应用程序上完整显示一个特定的页面(无需滚动 iframe) .
非常感谢您!
【问题讨论】:
-
我认为如果它不是跨域 iframe,这个解决方案会起作用。我更新了帖子。我将不胜感激您能提供的任何帮助!谢谢@MonzoorTamal!