You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现指定域名加载Iframe及页面源码半保护机制?

嘿,这两个需求我刚好做过类似的场景,直接给你拆解实现方案,都是前端常用的页面嵌入和简单源码保护技巧:

一、仅允许指定域名加载Iframe,否则跳转整个页面

核心思路是判断当前页面是否处于iframe中,再验证嵌入来源的域名是否在白名单里,不符合就直接修改顶层窗口的地址实现跳转。

直接上代码(放在被嵌入的页面里,比如你的页面A):

// 允许嵌入的域名列表,务必包含http/https协议
const allowedDomains = ['https://your-allowed-domain.com'];

// 检查是否被嵌入,且来源不在白名单
if (window.top !== window.self) {
  const referrerOrigin = new URL(document.referrer).origin;
  if (!allowedDomains.includes(referrerOrigin)) {
    // 跳转整个页面到指定地址
    window.top.location.href = 'https://your-main-page.com';
  }
}

几个注意点:

  • 一定要带协议(http/https),因为origin返回的是带协议的完整域名,只写your-allowed-domain.com会匹配失败
  • 如果要允许多个域名,直接往数组里加就行
  • 特殊场景下(比如同域名不同页面嵌入),可以用window.parent.location.origin替代document.referrer,后者更准确反映嵌入来源
二、A/B/C页面的半保护源码机制

这个机制的核心是用B页面做“中转容器”,A页面只允许被B加载,直接访问就跳转到C。下面分页面讲实现:

1. 页面B(全屏容器页)

B页面就是个纯iframe壳子,没有多余内容,让iframe占满整个窗口,用户看起来就像直接访问A:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>容器页B</title>
  <style>
    html, body {
      margin: 0;
      padding: 0;
      overflow: hidden;
    }
    iframe {
      width: 100vw;
      height: 100vh;
      border: none;
      display: block;
    }
  </style>
</head>
<body>
  <!-- sandbox属性可选,用来限制iframe权限,需要交互就放开对应权限 -->
  <iframe src="/path/to/page-A.html" sandbox="allow-same-origin allow-scripts"></iframe>
</body>
</html>

2. 页面A(内容页)

A页面要做两个判断:是否被直接访问,是否被正确的B页面嵌入,不符合就跳转到C:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>内容页A</title>
  <script>
    // 页面B的完整URL,或者只验证域名也行
    const allowedParentUrl = 'https://your-domain.com/page-B.html';

    // 直接访问的情况
    if (window.top === window.self) {
      window.location.href = '/path/to/page-C.html';
    } else {
      // 被嵌入但不是B页面的情况
      if (window.top.location.href !== allowedParentUrl) {
        window.top.location.href = '/path/to/page-C.html';
      }
    }
  </script>
</head>
<body>
  <!-- 这里是你的全部数据内容 -->
  <h1>只有通过B页面加载才能看到我</h1>
  <script>
    // 业务脚本,加载后控制台能看到数据
    const yourData = { id: 1, content: '敏感内容示例' };
    console.log('页面数据:', yourData);
  </script>
</body>
</html>

3. 页面C(主页面)

C就是正常的网站首页,不需要特殊处理,比如:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>主页面C</title>
</head>
<body>
  <h1>欢迎来到主站</h1>
  <p>请通过<a href="/path/to/page-B.html">正确入口</a>查看内容</p>
</body>
</html>

关于“半保护”的说明

要注意,这种方式只是阻止普通用户直接看到A的内容,并不是真正的源码加密:

  • 懂技术的人可以通过浏览器网络面板直接下载A的源码
  • 禁用JavaScript后访问A,跳转逻辑失效,就能看到内容
  • 控制台的数据也能被查看

如果要真正保护源码,得配合后端做鉴权、内容加密(比如后端渲染加密内容,前端解密)等操作。

内容的提问来源于stack exchange,提问作者Samoussa Binou Mymusicisinme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:56:03