当前位置:首页 > JavaScript

js实现frame

2026-04-05 17:14:08JavaScript

使用 iframe 嵌入外部页面

在 HTML 中直接使用 <iframe> 标签是最简单的方法:

<iframe src="https://example.com" width="800" height="600"></iframe>

动态创建 iframe

通过 JavaScript 动态创建 iframe 元素:

js实现frame

const frame = document.createElement('iframe');
frame.src = 'https://example.com';
frame.width = '800';
frame.height = '600';
document.body.appendChild(frame);

控制 iframe 内容

通过 contentWindowcontentDocument 访问 iframe 内部:

const iframe = document.querySelector('iframe');
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
iframeDoc.body.style.backgroundColor = 'red';

跨域通信

使用 postMessage 实现跨域通信:

js实现frame

// 父页面发送消息
iframe.contentWindow.postMessage('Hello', 'https://example.com');

// iframe 内接收消息
window.addEventListener('message', (event) => {
  if (event.origin !== 'https://parent.com') return;
  console.log(event.data);
});

替代方案:div 模拟 frame

使用 div 和 object 标签模拟 frame 效果:

<div id="frameContainer" style="width:800px; height:600px; overflow:auto;">
  <object data="https://example.com" type="text/html"></object>
</div>

安全性考虑

设置 sandbox 属性限制 iframe 权限:

<iframe src="https://example.com" sandbox="allow-scripts allow-same-origin"></iframe>

标签: jsframe
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableEleme…

js实现全选

js实现全选

实现全选功能的方法 在JavaScript中实现全选功能通常涉及监听全选复选框的点击事件,并根据其状态控制其他复选框的选中状态。以下是几种常见的实现方式: 基础DOM操作实现 通过获取所有目标复选框…

js实现报表

js实现报表

使用JavaScript实现报表 在JavaScript中实现报表功能可以通过多种方式完成,常见的方法包括使用原生JavaScript、第三方库(如Chart.js、D3.js)或结合后端数据渲染。以…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…

js 实现递归

js 实现递归

递归的基本概念 递归是指函数直接或间接调用自身的过程。在JavaScript中,递归通常用于解决可以分解为相似子问题的问题,如阶乘、斐波那契数列、树形结构遍历等。 递归的实现要点 基线条件(Base…

js实现删除

js实现删除

使用 splice 方法删除数组元素 splice 方法可以删除数组中的元素,并返回被删除的元素。它接受两个参数:起始索引和要删除的元素数量。 const array = [1, 2, 3, 4…