基于ChromeDp的多标签页开发
2022-12-01 11:56:44

最近恰逢世界杯,公司的剪辑业务蹭了一波热度,开发了一个活动页面,其中有个截图功能,目前的实现方式是,一个截图请求对应打开一个chrome进程。因为考虑到一瞬间流量打进来导致会打开N个浏览器进程 进而可能会有导致服务器内存增大的风险。所以临时接到任务,想要改写截图的逻辑,最好可以保持一个chrome进程,使用多选项卡的方式,请求完成后关闭选项卡,达到一个优化的效果

实现方式如下,主要是为了自己的记忆:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main

import (
"context"
"fmt"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"github.com/gin-gonic/gin"
)


var ChromeCtx context.Context
var AllocateCancel context.Context
var Cancel context.CancelFunc

func main(){
Ctx, Cancel = initContext()
g := gin.Default()

g.Handle("GET", "/", func(c *gin.Context) {
url := c.Query("url")
visit(url)
})

g.Run(":8888")

// 服务关闭后 关闭浏览器进程
defer AllocateCancel()
defer Cancel()
}
func initContext() (context.Context, context.CancelFunc) {
//chrome配置
opts := append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.DisableGPU,
chromedp.Flag("headless", false),
chromedp.Flag("enable-automation", false),
chromedp.Flag("restore-on-startup", false),
)

//创建allocator上下文 我的理解为浏览器的上下文 打开浏览器进程
allocCtx,AllocateCtx := chromedp.NewExecAllocator(context.Background(),opts..)

//创建请求的上下文
ctx, cancel := chromedp.NewContext(allocCtx)
//固定打开一个标签页
_ = chromedp.Run(ctx, chromedp.Navigate("about:blank"))

return ctx, cancel
}

func visit(url string){
tmpCtx, tmpCancel := chromedp.NewContext(Ctx)

// 打开一个新的tab
if err := chromedp.Run(tmpCtx, chromedp.Navigate(url)); err != nil {
panic(err)
}

// 请求完后关闭当前tab
err := page.Close().Do(cdp.WithExecutor(tmpCtx, chromedp.FromContext(tmpCtx).Target))
if err != nil {
fmt.Println(err)
return
}
Ctx,Cancel = tmpCtx,tmpCancel
}