Files
go-taobao/libs/chrome.go
2026-02-09 16:05:56 +08:00

80 lines
2.2 KiB
Go

package libs
import (
"log"
"path/filepath"
"strconv"
"github.com/go-rod/rod"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod/lib/proto"
"github.com/go-rod/stealth"
)
// Chrome 浏览器创建器
type Chrome struct{}
// Create 创建一个带反检测的 Chrome 浏览器实例
func (c *Chrome) Create(accountId int, params *Fingerprint) (*rod.Browser, string, *rod.Page) {
userDataDir := "user-data/" + strconv.Itoa(accountId)
absPath, _ := filepath.Abs(userDataDir)
log.Printf("[Chrome] 用户数据目录: %s", absPath)
chromePath, _ := launcher.LookPath()
l := launcher.New().
Bin(chromePath).
Delete("use-mock-keychain").
// 反自动化检测
Set("disable-blink-features", "AutomationControlled").
Set("excludeSwitches", "enable-automation").
Set("disable-infobars", "true").
// 数据持久化 & 窗口
Set("user-data-dir", absPath).
Set("window-size", "1920,1480").
// 性能 & 安全
Set("no-sandbox", "true").
Set("enable-gpu").
Set("ignore-certificate-errors").
Set("disable-application-cache").
Set("disable-dev-shm-usage").
// 媒体
Set("use-fake-ui-for-media-stream").
Set("autoplay-policy", "no-user-gesture-required").
// 隐私: 禁用 WebRTC 防止 IP 泄露
Set("disable-webrtc", "true").
Set("disable-features", "WebRtcHideLocalIpsWithMdns").
Set("webrtc-ip-handling-policy", "disable_non_proxied_udp").
Set("force-webrtc-ip-handling-policy").
// 跨域 & 通知
Set("disable-web-security", "true").
Set("disable-notifications", "true").
Set("disable-site-isolation-trials", "true").
Set("disable-geolocation", "true").
Headless(false)
uri := l.MustLaunch()
browser := rod.New().
ControlURL(uri).
MustConnect().
NoDefaultDevice()
browser.MustIgnoreCertErrors(true)
// 使用 stealth 模式创建页面
page := stealth.MustPage(browser)
// 为所有新打开的页面也注入 stealth 脚本
go browser.EachEvent(func(e *proto.TargetTargetCreated) {
if e.TargetInfo.Type != proto.TargetTargetInfoTypePage {
return
}
browser.MustPageFromTargetID(e.TargetInfo.TargetID).MustEvalOnNewDocument(stealth.JS)
})()
page.MustSetViewport(1920, 1480, 1.0, false)
log.Printf("[Chrome] 浏览器已启动 (账号 #%d)", accountId)
return browser, uri, page
}