react 如何内嵌他人页面
使用 iframe 嵌入外部页面
在 React 中嵌入外部页面最直接的方法是使用 <iframe> 标签。这种方式简单且兼容性高,适用于大多数场景。
function EmbeddedPage() {
return (
<iframe
src="https://example.com"
width="100%"
height="500px"
title="External Page"
/>
);
}
可以通过调整 width 和 height 属性控制嵌入页面的尺寸。建议添加 title 属性以提升可访问性。
处理跨域限制
嵌入的页面如果与当前域名不同,可能会受到浏览器同源策略的限制。这种情况下,嵌入的页面无法与父页面进行 JavaScript 交互。
对于需要双向通信的场景,可以使用 postMessage API 实现跨域通信:

function EmbeddedPage() {
useEffect(() => {
window.addEventListener('message', (event) => {
// 验证来源域名
if (event.origin !== 'https://example.com') return;
console.log('Received message:', event.data);
});
return () => window.removeEventListener('message');
}, []);
const sendMessage = () => {
const iframe = document.getElementById('myIframe');
iframe.contentWindow.postMessage('Hello', 'https://example.com');
};
return (
<>
<iframe
id="myIframe"
src="https://example.com"
width="100%"
height="500px"
title="External Page"
/>
<button onClick={sendMessage}>Send Message</button>
</>
);
}
使用 react-frame-component 库
对于更复杂的嵌入需求,可以使用专门的 React 库如 react-frame-component。这个库提供了更好的 React 组件集成方式。
安装依赖:
npm install react-frame-component
使用示例:

import Frame from 'react-frame-component';
function EmbeddedPage() {
return (
<Frame
src="https://example.com"
initialContent='<!DOCTYPE html><html><head></head><body><div id="mountHere"></div></body></html>'
mountTarget='#mountHere'
style={{ width: '100%', height: '500px' }}
/>
);
}
安全性考虑
嵌入第三方页面时需注意安全风险:
- 避免嵌入不可信的网站,防止 XSS 攻击
- 设置
sandbox属性限制 iframe 权限 - 对于敏感操作,考虑使用代理服务中转内容
示例带沙盒限制的 iframe:
<iframe
src="https://example.com"
sandbox="allow-same-origin allow-scripts"
width="100%"
height="500px"
/>
响应式设计处理
为了使嵌入页面适应不同屏幕尺寸,可以结合 CSS 实现响应式设计:
<div style={{ position: 'relative', overflow: 'hidden', paddingTop: '56.25%' }}>
<iframe
src="https://example.com"
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
border: 0
}}
allowFullScreen
/>
</div>
这种设计保持 16:9 的宽高比,适合视频等内容嵌入。






