You need to enable JavaScript to run this app. 如何通过HTML/JavaScript/PHP实现点击打开网页view-source源码功能
优惠活动
大模型
产品
解决方案
定价
更多

如何通过HTML/JavaScript/PHP实现点击打开网页view-source源码功能

问题原因及修复方案

问题原因

你遇到的是主流浏览器的默认安全限制:

  1. 所有现代浏览器都禁止通过页面内的<a>标签跳转、window.open()调用访问view-source:协议地址,避免被恶意站点利用进行欺骗行为。
  2. 你原有代码中页面加载完成后自动调用window.open()的逻辑,也会被浏览器的弹窗拦截规则直接拦截,只有用户主动点击交互触发的弹窗才会被放行。

推荐解决方案:纯前端实现(适配纯静态站点需求)

不需要后端支持,完全运行在用户端,拿到的源码和浏览器view-source结果完全一致,可以直接证明站点无追踪脚本、无后端逻辑。

方案1:读取渲染后源码(适合完全无动态DOM修改的纯静态页)

function openPageSource() {
  // 拼接完整HTML源码
  const sourceCode = '<!DOCTYPE html>\n' + document.documentElement.outerHTML;
  // 打开新标签页
  const newWin = window.open('');
  // 写入格式化的源码展示页面
  newWin.document.write(`
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>页面源代码</title>
  <style>
    pre {
      margin: 0;
      padding: 20px;
      background: #f5f5f5;
      font-size: 14px;
      line-height: 1.6;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
  </style>
</head>
<body>
  <pre>${sourceCode.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>
</body>
</html>
  `);
  newWin.document.close();
}

对应的触发元素写法:

<!-- 链接写法 -->
<a href="javascript:void(0)" onclick="openPageSource()">查看页面源代码</a>

<!-- 按钮写法 -->
<button onclick="openPageSource()">查看页面源代码</button>

方案2:请求原始静态源码(和view-source结果100%一致,适配所有场景)

如果你的页面存在JS动态修改DOM的逻辑,用这个方案可以直接拿到服务器返回的原始源码:

async function openPageSource() {
  // 请求当前页面地址,拿到原始返回内容
  const res = await fetch(window.location.href);
  const sourceCode = await res.text();
  const newWin = window.open('');
  newWin.document.write(`
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>页面源代码</title>
  <style>
    pre {
      margin: 0;
      padding: 20px;
      background: #f5f5f5;
      font-size: 14px;
      line-height: 1.6;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
  </style>
</head>
<body>
  <pre>${sourceCode.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>
</body>
</html>
  `);
  newWin.document.close();
}

触发元素写法和方案1一致。

可选方案:PHP实现(需后端支持,不推荐纯静态站点使用)

如果你的站点允许使用PHP,可以新增一个source.php文件读取页面源码返回:

<?php
header('Content-Type: text/plain; charset=utf-8');
// 替换为你实际的静态页面路径
echo file_get_contents('index.html');
?>

然后链接直接指向这个PHP文件即可:

<a href="source.php" target="_blank">查看页面源代码</a>

内容的提问来源于stack exchange,提问作者Charles Porth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 15:12:02