// src\content\common\user_agent.cc

std::string BuildUserAgentFromOSAndProduct(const std::string& os_info,
                                           const std::string& product) {
  // Derived from Safari's UA string.
  // This is done to expose our product name in a manner that is maximally
  // compatible with Safari, we hope!!
  std::string user_agent;
  base::StringAppendF(&user_agent,
                      "Mozilla/5.0 (%s) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "%s Safari/537.36",
                      os_info.c_str(), product.c_str());
  return user_agent;
}

修改文件位于src\content\common\user_agent.cc 找到BuildUserAgentFromProduct函数,需要注意的是,由于chrome源码为多端编译,注意在不同的BUILDFLAG下所以会存在多个类似BuildUserAgentFromProduct的函数,但名称不一定一样,可以考虑使用关键字UserAgent进行搜索类似的函数直接修改return的内容即可,下面是添加了从command_line中读取自定义user_agent的代码案例 。

// 添加command_line.h
#include "base/command_line.h"

std::string BuildUserAgentFromOSAndProduct(const std::string& os_info,
                                           const std::string& product) {
  // Derived from Safari's UA string.
  // This is done to expose our product name in a manner that is maximally
  // compatible with Safari, we hope!!
  GetUserAgentPlatform();
  const base::CommandLine* command_line =
      base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch("user-agent")) {
    return command_line->GetSwitchValueASCII("user-agent");
  }
  return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, "
         "like Gecko) Chrome/128.0.0.0 Safari/537.36";
}

如此,默认情况下,会返回一个固定的user_agent,但是如果在浏览器启动的时候添加一个参数--user_agent="xxx",则系统的userAgent将会根据你的输入被改变。

那么现在看一下显示效果,首先编译chrome后发送一个快捷方式到桌面,右击快捷方式,目标添加启动参数--user-agent="123123123213"

可以看到我们修改的内容立刻生效了!