当前位置:首页 > 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 元素:

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 实现跨域通信:

// 父页面发送消息
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 权限:

js实现frame

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

标签: jsframe
分享给朋友:

相关文章

js实现全屏

js实现全屏

实现全屏的基本方法 使用JavaScript实现全屏功能主要依赖Element.requestFullscreen()方法。现代浏览器均支持此API,但不同浏览器可能需要添加前缀。 // 触发全屏…

js实现防洪

js实现防洪

防抖(Debounce)实现 防抖的核心思想是在事件触发后延迟执行回调函数,若在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口调整等场景。 function debounce(func,…

js实现上传文件

js实现上传文件

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。 <input type="file"…

js计算器的实现

js计算器的实现

实现基础结构 HTML部分需要创建计算器的基本框架,包含显示区域和按钮。使用<div>容器包裹整个计算器,内部设置一个显示屏和多个按钮。 <div class="calculato…

js分页实现

js分页实现

分页的基本原理 分页的核心是通过计算当前页码和数据偏移量,从服务器或本地数据中截取对应范围的数据进行展示。通常需要以下参数:当前页码(currentPage)、每页条数(pageSize)、总数据量(…

js实现 拖动

js实现 拖动

实现拖动的步骤 HTML 结构 创建一个可拖动的元素和一个放置区域: <div id="draggable" draggable="true">拖动我</div> <d…