H5 referrer来源模拟

175 阅读2分钟

使用 http-server 起本地服务并模拟从百度跳转到 H5 页面,可以按照以下步骤进行:

步骤 1:安装 http-server

首先,确保你已经安装了 http-server

npm install -g http-server

步骤 2:创建本地服务文件

创建两个 HTML 文件,一个用于模拟百度跳转源页面,另一个用于 H5 目标页面。

  • index.html(模拟百度跳转源页面):

    <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Simulated Baidu Page</title>
        </head>
        <body>
            <h1>Simulated Baidu Page</h1>
            <a href="https://dev.kjs-m.xxx.com">Go to Target Page</a>
        </body>
    </html>
    
  • target.html(H5 目标页面):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Target Page</title>
</head>
<body>
    <h1>Target Page</h1>
    <p id="referrer"></p>
    <script>
        document.getElementById('referrer').textContent = document.referrer;
    </script>
</body>
</html>

步骤 3:启动 http-server

在包含 index.htmltarget.html 文件的目录中启动 http-server

http-server -p 8080

这将在端口 8080 上启动一个本地服务器。

步骤 4:修改 hosts 文件(可选)

为了更真实地模拟百度跳转,可以在本地 hosts 文件中添加一个虚拟域名。例如,将 localhost.baidu.com 映射到 127.0.0.1

Windows

在管理员模式下打开记事本,然后编辑 C:\Windows\System32\drivers\etc\hosts 文件,添加以下行:

127.0.0.1 localhost.baidu.com

macOS / Linux

打开终端并使用管理员权限编辑 /etc/hosts 文件:

sudo nano /etc/hosts

添加以下行:

127.0.0.1 localhost.baidu.com

步骤 5:访问模拟页面 --- 如果有翻墙代理一定要关闭

  1. 打开浏览器,访问 http://localhost.baidu.com:8080/index.html
  2. 点击链接跳转到 target.html
  3. target.html 页面中,document.referrer 应该会显示 http://localhost.baidu.com:8080/index.html

这样,你就成功地模拟了从百度跳转到 H5 页面,并可以测试 document.referrer 的行为。

macOS 如何修改并保存hosts 文件

步骤 1:打开终端

你可以通过以下几种方法打开终端:

  • 在 Spotlight 搜索中输入 "Terminal" 并回车。
  • 前往应用程序 -> 实用工具 -> 终端。

步骤 2:编辑 hosts 文件

在终端中,输入以下命令以编辑 hosts 文件:

sudo nano /etc/hosts

步骤 3:输入密码

系统会要求输入管理员密码。输入密码后按下回车键。

步骤 4:修改 hosts 文件

使用键盘上的箭头键浏览 hosts 文件。在文件的末尾或你想要修改的位置添加新的条目。例如,添加一行来映射 localhost.baidu.com127.0.0.1

127.0.0.1 localhost.baidu.com

步骤 5:保存修改

按下 Control + O 组合键保存文件。按下回车确认。

步骤 6:退出 nano 编辑器

按下 Control + X 组合键退出 nano 编辑器。

步骤 7:清除 DNS 缓存(可选)

为了确保修改生效,你可以清除 DNS 缓存。在终端中输入以下命令:

sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

步骤 8:验证修改 --- 如果有翻墙代理一定要关闭

打开浏览器,输入 http://localhost.baidu.com:8080/index.html 访问你的模拟页面,检查是否生效。

现在你已经成功修改并保存了 hosts 文件,并将 localhost.baidu.com 映射到了 127.0.0.1