发布时间:2025-12-09 16:06:17 浏览次数:6
iframe(内嵌框架)是 HTML 中一种用于将一个网页嵌入到另一个网页中的标签,它可以在一个页面中显示来自其他页面的内容。在网页中,使用<iframe>标签可以将一个网页嵌套在另一个网页中,实现网页间的互联互通。
<iframe>标签的基本用法如下:
<iframe src="URL"></iframe>| allow | 允许特定功能的列表,如fullscreen,geolocation等 |
| allowfullscreen | 指定是否允许在iframe中使用全屏模式 |
| allowpaymentrequest | 指定是否允许在iframe中进行支付请求 |
| allowtransparency | 指定iframe是否可以是透明的 |
| class | 为iframe定义一个或多个类名 |
| frameborder | 指定是否在iframe周围显示边框 |
| height | 指定iframe的高度 |
| importance | 指定iframe对页面内容的重要性 |
| loading | 指定iframe加载时的行为 |
| name | 为iframe定义一个名称 |
| referrerpolicy | 指定如何发送referer HTTP标头 |
| sandbox | 启用iframe的沙盒模式,提高安全性 |
| src | 指定要在iframe中显示的文档的URL |
| srcdoc | 在iframe中嵌入HTML代码而不是外部文档 |
| style | 定义iframe的CSS样式 |
| title | 为iframe定义一个标题 |
| width | 指定iframe的宽度 |
虽然 <iframe> 标签可以很方便地实现上述功能,但是需要注意以下几点:
总之,在使用 <iframe> 标签时,需要仔细权衡其优缺点,确保安全和性能。
可以在iframe的src属性中使用查询参数(也称为URL参数)将数据传递到嵌入的页面。例如,假设iframe嵌入的页面URL是 index.com/page.html,那么可以使用如下的URL来传递数据:
<iframe src="index.com/page.html?param1=value1¶m2=value2"></iframe>在嵌入的页面中,可以使用JavaScript获取查询参数并使用它们:
var params = new URLSearchParams(window.location.search);var param1 = params.get('param1');var param2 = params.get('param2');或者写一个函数获取对应的值(该方法来自拓维的一位前端工程师大佬):
//从url获取参数export const getQuery = (name: string, url?: string) => {const params = new URLSearchParams(url || window.location.search);const value = params.get(name);if (value) {return value;}return getQueryString(name, url);};export const getQueryString = (name: string, url?: string) => {const reg = new RegExp('(^|&|/?)' + name + '=([^&]*)(&|$)', 'i');const r = encodeURI(url || window.location.search || window.location.href || window.location.hash).substr(1).match(reg);if (r != null) return unescape(r[2]);return null;};postMessage()方法是一种用于在不同窗口或文档之间传递消息的通用方法,它可以实现跨域通信。在使用postMessage()方法时,需要在发送消息的窗口(发送方)和接收消息的窗口(接收方)中分别编写代码。
子:
// 发送消息给接收方窗口window.parent.postMessage("Hello, parent!", "http://parent.com");父:
// 监听message事件,接收消息window.addEventListener("message", receiveMessage, false);function receiveMessage(event) {// 判断消息来源是否是指定的发送方窗口if (event.origin === "http://child.com") {// 处理接收到的消息console.log(event.data);}}父:
创建实例对象:
const iframe = document.getElementById('my-iframe');const iframeWindow = iframe.contentWindow;发送消息:
const message = { type: 'GREETINGS', data: 'Hello, child!' };const targetOrigin = 'http://child.com'; // 指定接收方的源iframeWindow.postMessage(message, targetOrigin);子:
接收消息
window.addEventListener('message', receiveMessage, false);function receiveMessage(event) {if (event.origin === 'http://parent.com') { // 验证消息来源console.log(event.data); // 处理接收到的消息}}注意:可以将 targetOrigin 设置为“ * ” 号以匹配所有路径,但可能会有安全风险。谨慎使用。