谷歌浏览器和火狐浏览器对HTML的嗅探(Sniff)能力

如下样例代码, 返回网站首页HTML内容

java 复制代码
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Objects;


@Controller
@RequestMapping
public class FrontController {

    @ResponseBody
    @GetMapping("/")
    public void store(HttpServletRequest request) {
        String homePage = "http://t.infuq.com/data/static/sniff.html";
        /** http://t.infuq.com/data/static/sniff.html 内容如下
<!--
2025.10.22
-->
<!DOCTYPE html>
<html lang>
    <head>
        <meta charset="utf-8">
        <title>MyTitle</title>
    </head>
    <body>
        <p>https://www.infuq.com http://t.infuq.com</p>
    </body>
</html>
        */
        read(homePage);
    }

    private void read(String url) {
        InputStream in = ResourceUtils.getURL(url).openStream();
        HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
        IOUtils.copy(in, response.getOutputStream());
    }
}

当通过 Chrome 或 Microsoft Edge 访问时可以正常显示内容如下

但是通过火狐浏览器访问时, 却显示了源码

查看响应头信息

服务端没有返回Content-Type, 火狐浏览器(64位 v144.0)通过嗅探能力, 判断该文件是text/plain文件, 而 Chrome 等浏览器会把该文件识别成text/html文件.

【解决】

1.在服务端指定响应Content-Type

response.setContentType("text/html");

2.将HTML源码顶部的注释去掉

html 复制代码
把
<!--
2025.10.22
-->
<!DOCTYPE html>
<html lang>
    <head>
        <meta charset="utf-8">
        <title>MyTitle</title>
    </head>
    <body>
        <p>https://www.infuq.com http://t.infuq.com</p>
    </body>
</html>

改成 
<!DOCTYPE html>
<html lang>
    <head>
        <meta charset="utf-8">
        <title>MyTitle</title>
    </head>
    <body>
        <p>https://www.infuq.com http://t.infuq.com</p>
    </body>
</html>

https://source.chromium.org/chromium/chromium/src/+/refs/tags/118.0.5981.4:net/base/mime_sniffer.cc

相关推荐
rocky1914 小时前
谷歌浏览器插件 使用 playwright 回放用户动作键盘按键特殊处理方案
前端
rocky1914 小时前
playwright里兼容处理回放无界微前端内iframe内部元素事件和不在无界微前端内的iframe元素
前端
rocky1914 小时前
谷歌浏览器插件 使用 playwright 回放slide 拖动动作
前端
惺忪97984 小时前
回调函数的概念
开发语言·前端·javascript
前端 贾公子4 小时前
Element Plus组件v-loading在el-dialog组件上使用无效
前端·javascript·vue.js
天外飞雨道沧桑4 小时前
JS/CSS实现元素样式隔离
前端·javascript·css·人工智能·ai
程序0074 小时前
前端写一个密码登录,验证码登录,注册模板
前端
-曾牛5 小时前
从零到一:XSS靶场 haozi.me 全关卡通关教程(含冷知识汇总)
前端·网络安全·渗透测试·靶场·xss·攻略·靶场教程
qq_419854055 小时前
自定义组件(移动端下拉多选)中使用 v-model
前端·javascript·vue.js