使用 <iframe>
嵌入外部网页
说明
通过 <iframe>
标签可以直接嵌入其他网站的完整页面或部分内容,适用于展示第三方网页、视频、地图等。
src
width
/height
frameborder
0
或 "no"
表示无边框)sandbox
示例
<iframe src="https://example.com" width="600" height="400" sandbox="allow-scripts"></iframe>
通过 JavaScript 动态加载外部资源
说明
使用 fetch
或 XMLHttpRequest
请求其他网站的 API 或数据,需目标服务器允许跨域(CORS)。
方法 | 说明 |
---|---|
fetch |
现代浏览器支持,返回 Promise,需处理 JSON 数据或二进制流 |
XMLHttpRequest |
传统方式,需手动处理异步回调和状态码 |
示例(fetch
)
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { console.log(data); // 将数据渲染到页面 }) .catch(error => console.error('跨域请求失败:', error));
使用 Web Components 封装外部内容
说明
通过自定义元素(如 <web-component>
)封装外部资源,适合复用组件化逻辑。
示例(简化版)
<script> class WebComponent extends HTMLElement { connectedCallback() { this.innerHTML = `<iframe src="https://example.com" width="100%" height="300"></iframe>`; } } customElements.define('web-component', WebComponent); </script> <web-component></web-component>
常见问题与解答
问题 1:<iframe>
加载外部页面时出现空白或跨域错误?
解答:
- 检查目标网站是否允许嵌入(部分网站设置
X-Frame-Options
或Content-Security-Policy
)。 - 若目标站点禁止嵌入,需联系对方启用允许,或通过代理服务器中转请求。
问题 2:如何安全地调用其他网站的 API?
解答:
- 确保目标 API 支持 CORS,且域名在服务器端配置了允许列表。
- 使用 HTTPS 加密通信,避免敏感数据泄露。
- 对返回数据进行校验和过滤,防止 XSS 攻击