Repository navigation
Expand file tree
/
Copy pathscreenshot_utils.go
More file actions
91 lines (74 loc) · 2.07 KB
/
Copy pathscreenshot_utils.go
File metadata and controls
91 lines (74 loc) · 2.07 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package devbrowser
import (
"fmt"
"webtyp.com/devbrowser/chromedp"
)
// ScreenshotResult contains the image data and metadata about the captured page.
type ScreenshotResult struct {
ImageData []byte
PageTitle string
PageURL string
Width int
Height int
HTMLStructure string
}
// CaptureScreenshot captures a screenshot of the current page.
func (b *DevBrowser) CaptureScreenshot(fullpage bool) (*ScreenshotResult, error) {
if !b.IsOpenFlag || b.Ctx == nil {
return nil, fmt.Errorf("browser is not open")
}
var buf []byte
var err error
if fullpage {
err = chromedp.Run(b.toolCtx(),
chromedp.FullScreenshot(&buf, 90),
)
} else {
err = chromedp.Run(b.toolCtx(),
chromedp.CaptureScreenshot(&buf),
)
}
if err != nil {
return nil, fmt.Errorf("failed to capture screenshot: %v", err)
}
res := &ScreenshotResult{
ImageData: buf,
}
// Capture comprehensive page context
err = chromedp.Run(b.toolCtx(),
chromedp.Title(&res.PageTitle),
chromedp.Location(&res.PageURL),
chromedp.Evaluate(`window.innerWidth`, &res.Width),
chromedp.Evaluate(`window.innerHeight`, &res.Height),
chromedp.Evaluate(GetStructureJS, &res.HTMLStructure),
)
if err != nil {
// Non-fatal, return what we have
b.Logger(fmt.Sprintf("Warning: failed to capture context metadata: %v", err))
}
return res, nil
}
// CaptureElementScreenshot captures a screenshot of a specific element.
func (b *DevBrowser) CaptureElementScreenshot(selector string) (*ScreenshotResult, error) {
if !b.IsOpenFlag || b.Ctx == nil {
return nil, fmt.Errorf("browser is not open")
}
var buf []byte
err := chromedp.Run(b.toolCtx(),
chromedp.Screenshot(selector, &buf),
)
if err != nil {
return nil, fmt.Errorf("failed to capture element screenshot: %v", err)
}
res := &ScreenshotResult{
ImageData: buf,
}
// Capture basic context
_ = chromedp.Run(b.toolCtx(),
chromedp.Title(&res.PageTitle),
chromedp.Location(&res.PageURL),
chromedp.Evaluate(`window.innerWidth`, &res.Width),
chromedp.Evaluate(`window.innerHeight`, &res.Height),
)
return res, nil
}