From 57fa45fb3cd93601f6e69b7e075baa6f3ef9c0bb Mon Sep 17 00:00:00 2001 From: Nanite Factory Date: Thu, 12 Dec 2019 23:34:02 +0900 Subject: [PATCH] init --- .gitignore | 4 + LICENSE | 21 + README.md | 52 +++ builder.go | 243 ++++++++++++ builder_test.go | 42 ++ chrome.go | 160 ++++++++ chrome_test.go | 113 ++++++ doc.go | 4 + domain/accessibility.go | 75 ++++ domain/animation.go | 131 ++++++ domain/applicationcache.go | 65 +++ domain/audits.go | 41 ++ domain/backgroundservice.go | 59 +++ domain/browser.go | 216 ++++++++++ domain/cachestorage.go | 88 ++++ domain/cast.go | 74 ++++ domain/css.go | 325 +++++++++++++++ domain/database.go | 64 +++ domain/debugger.go | 480 ++++++++++++++++++++++ domain/deviceorientation.go | 35 ++ domain/dom.go | 706 +++++++++++++++++++++++++++++++++ domain/domain.go | 241 +++++++++++ domain/domdebugger.go | 138 +++++++ domain/domsnapshot.go | 57 +++ domain/domstorage.go | 82 ++++ domain/emulation.go | 321 +++++++++++++++ domain/fetch.go | 165 ++++++++ domain/har.go | 12 + domain/headlessexperimental.go | 64 +++ domain/heapprofiler.go | 161 ++++++++ domain/indexeddb.go | 139 +++++++ domain/input.go | 300 ++++++++++++++ domain/inspector.go | 30 ++ domain/io.go | 63 +++ domain/layertree.go | 153 +++++++ domain/log.go | 59 +++ domain/media.go | 30 ++ domain/memory.go | 130 ++++++ domain/network.go | 365 +++++++++++++++++ domain/overlay.go | 277 +++++++++++++ domain/page.go | 671 +++++++++++++++++++++++++++++++ domain/performance.go | 55 +++ domain/profiler.go | 142 +++++++ domain/runtime.go | 425 ++++++++++++++++++++ domain/security.go | 42 ++ domain/serviceworker.go | 155 ++++++++ domain/storage.go | 90 +++++ domain/systeminfo.go | 39 ++ domain/target.go | 253 ++++++++++++ domain/tethering.go | 36 ++ domain/tracing.go | 92 +++++ domain/webaudio.go | 45 +++ domain/webauthn.go | 135 +++++++ example_test.go | 68 ++++ go.mod | 9 + go.sum | 16 + tab.go | 117 ++++++ tab_test.go | 63 +++ 58 files changed, 8238 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 builder.go create mode 100644 builder_test.go create mode 100644 chrome.go create mode 100644 chrome_test.go create mode 100644 doc.go create mode 100644 domain/accessibility.go create mode 100644 domain/animation.go create mode 100644 domain/applicationcache.go create mode 100644 domain/audits.go create mode 100644 domain/backgroundservice.go create mode 100644 domain/browser.go create mode 100644 domain/cachestorage.go create mode 100644 domain/cast.go create mode 100644 domain/css.go create mode 100644 domain/database.go create mode 100644 domain/debugger.go create mode 100644 domain/deviceorientation.go create mode 100644 domain/dom.go create mode 100644 domain/domain.go create mode 100644 domain/domdebugger.go create mode 100644 domain/domsnapshot.go create mode 100644 domain/domstorage.go create mode 100644 domain/emulation.go create mode 100644 domain/fetch.go create mode 100644 domain/har.go create mode 100644 domain/headlessexperimental.go create mode 100644 domain/heapprofiler.go create mode 100644 domain/indexeddb.go create mode 100644 domain/input.go create mode 100644 domain/inspector.go create mode 100644 domain/io.go create mode 100644 domain/layertree.go create mode 100644 domain/log.go create mode 100644 domain/media.go create mode 100644 domain/memory.go create mode 100644 domain/network.go create mode 100644 domain/overlay.go create mode 100644 domain/page.go create mode 100644 domain/performance.go create mode 100644 domain/profiler.go create mode 100644 domain/runtime.go create mode 100644 domain/security.go create mode 100644 domain/serviceworker.go create mode 100644 domain/storage.go create mode 100644 domain/systeminfo.go create mode 100644 domain/target.go create mode 100644 domain/tethering.go create mode 100644 domain/tracing.go create mode 100644 domain/webaudio.go create mode 100644 domain/webauthn.go create mode 100644 example_test.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 tab.go create mode 100644 tab_test.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3b1257a --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*.log +debug +*.exe +__ignore/ \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7cf40ec --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 NaniteFactory + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..4e3cbec --- /dev/null +++ b/README.md @@ -0,0 +1,52 @@ +# Chromebot + +[![GoDoc](https://godoc.org/github.com/nanitefactory/chromebot?status.svg)](https://godoc.org/github.com/nanitefactory/chromebot) + +Package `chromebot` provides a high-level interface to automate tasks in Chrome or Chromium. Work based on [chromedp](https://github.com/chromedp/chromedp). + +## Installation + +```Cmd +go get -v github.com/nanitefactory/chromebot +``` + +## Test + +```Cmd +go test -v github.com/nanitefactory/chromebot +``` + +## Quick start + +```Go +// Start a browser +browser := chromebot.New(false) +defer browser.Close() + +// Navigate +browser.Tab(0).Run( + chromedp.Navigate("https://godoc.org"), + chromedp.WaitVisible("html"), +) + +// Another navigation method +// browser.Tab(0).Do().Page().Navigate("https://godoc.org", nil, nil, nil) + +// Get cookies +cookies, err := browser.Tab(0).Do().Network().GetAllCookies() +if err != nil { + panic(err) +} + +// Print +for i, cookie := range cookies { + fmt.Println(i, cookie) +} + +// _Output: +// 0 &{__utma 58978491.1884756898.1576137201.1576137201.1576137201.1 .godoc.org / 1.639209201e+09 60 false false false } +// 1 &{__utmc 58978491 .godoc.org / -1 14 false false true } +// 2 &{__utmz 58978491.1576137201.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .godoc.org / 1.591905201e+09 75 false false false } +// 3 &{__utmt 1 .godoc.org / 1.576137801e+09 7 false false false } +// 4 &{__utmb 58978491.1.10.1576137201 .godoc.org / 1.576139001e+09 30 false false false } +``` diff --git a/builder.go b/builder.go new file mode 100644 index 0000000..977e5dd --- /dev/null +++ b/builder.go @@ -0,0 +1,243 @@ +package chromebot + +import ( + "context" + "sync" + "time" + + "github.com/chromedp/chromedp" +) + +// Builder builds a Chrome instance. +type Builder struct { + deadline *time.Time + eOpts []chromedp.ExecAllocatorOption + bOpts []chromedp.BrowserOption + cOpts []chromedp.ContextOption +} + +// NewBuilder is a constructor. +func NewBuilder() *Builder { + return &Builder{ + deadline: nil, + eOpts: []chromedp.ExecAllocatorOption{}, + bOpts: []chromedp.BrowserOption{}, + cOpts: []chromedp.ContextOption{}, + } +} + +// BuilderFlags is a set of generic command line options to pass as flags to Chrome. +type BuilderFlags struct { + NoFirstRun bool + NoDefaultBrowserCheck bool + Headless bool + HideScrollbars bool + MuteAudio bool + // + UserDataDir string // UserDataDir is the command line option to set the profile directory used by Chrome. + ProxyServer string // ProxyServer is the command line option to set the outbound proxy server. + WindowSize struct { + Width int + Height int + } + UserAgent string + NoSandbox bool + DisableGPU bool + // + DisableBackgroundNetworking bool + EnableFeatures string + DisableBackgroundTimerThrottling bool + DisableBackgroundingOccludedWindows bool + DisableBreakpad bool + DisableClientSidePhishingDetection bool + DisableDefaultApps bool + DisableDevShmUsage bool + DisableExtensions bool + DisableFeatures string + DisableHangMonitor bool + DisableIpcFloodingProtection bool + DisablePopupBlocking bool + DisablePromptOnRepost bool + DisableRendererBackgrounding bool + DisableSync bool + ForceColorProfile string + MetricsRecordingOnly bool + SafebrowsingDisableAutoUpdate bool + EnableAutomation bool + PasswordStore string + UseMockKeychain bool +} + +// DefaultBuilderFlags is a set of generic command line options to pass as flags to Chrome. +var DefaultBuilderFlags = BuilderFlags{ + NoFirstRun: true, + NoDefaultBrowserCheck: true, + Headless: true, + HideScrollbars: true, + MuteAudio: true, + // + UserDataDir: "", + ProxyServer: "", + WindowSize: struct { + Width int + Height int + }{-1, -1}, + UserAgent: "", + NoSandbox: false, + DisableGPU: false, + // + DisableBackgroundNetworking: true, + EnableFeatures: "NetworkService,NetworkServiceInProcess", + DisableBackgroundTimerThrottling: true, + DisableBackgroundingOccludedWindows: true, + DisableBreakpad: true, + DisableClientSidePhishingDetection: true, + DisableDefaultApps: true, + DisableDevShmUsage: true, + DisableExtensions: true, + DisableFeatures: "site-per-process,TranslateUI,BlinkGenPropertyTrees", + DisableHangMonitor: true, + DisableIpcFloodingProtection: true, + DisablePopupBlocking: true, + DisablePromptOnRepost: true, + DisableRendererBackgrounding: true, + DisableSync: true, + ForceColorProfile: "srgb", + MetricsRecordingOnly: true, + SafebrowsingDisableAutoUpdate: true, + EnableAutomation: true, + PasswordStore: "basic", + UseMockKeychain: true, +} + +// WithFlags sets a set of generic command line options to pass as flags to Chrome. +// Recommend use with `DefaultFlags`. +func (b *Builder) WithFlags(arg BuilderFlags) *Builder { + b.eOpts = append(b.eOpts, []chromedp.ExecAllocatorOption{ + chromedp.Flag("no-first-run", arg.NoFirstRun), + chromedp.Flag("no-default-browser-check", arg.NoDefaultBrowserCheck), + chromedp.Flag("headless", arg.Headless), + chromedp.Flag("hide-scrollbars", arg.HideScrollbars), + chromedp.Flag("mute-audio", arg.MuteAudio), + // + chromedp.Flag("no-sandbox", arg.NoSandbox), + chromedp.Flag("disable-gpu", arg.DisableGPU), + // + chromedp.Flag("disable-background-networking", arg.DisableBackgroundNetworking), + chromedp.Flag("enable-features", arg.EnableFeatures), + chromedp.Flag("disable-background-timer-throttling", arg.DisableBackgroundTimerThrottling), + chromedp.Flag("disable-backgrounding-occluded-windows", arg.DisableBackgroundingOccludedWindows), + chromedp.Flag("disable-breakpad", arg.DisableBreakpad), + chromedp.Flag("disable-client-side-phishing-detection", arg.DisableClientSidePhishingDetection), + chromedp.Flag("disable-default-apps", arg.DisableDefaultApps), + chromedp.Flag("disable-dev-shm-usage", arg.DisableDevShmUsage), + chromedp.Flag("disable-extensions", arg.DisableExtensions), + chromedp.Flag("disable-features", arg.DisableFeatures), + chromedp.Flag("disable-hang-monitor", arg.DisableHangMonitor), + chromedp.Flag("disable-ipc-flooding-protection", arg.DisableIpcFloodingProtection), + chromedp.Flag("disable-popup-blocking", arg.DisablePopupBlocking), + chromedp.Flag("disable-prompt-on-repost", arg.DisablePromptOnRepost), + chromedp.Flag("disable-renderer-backgrounding", arg.DisableRendererBackgrounding), + chromedp.Flag("disable-sync", arg.DisableSync), + chromedp.Flag("force-color-profile", arg.ForceColorProfile), + chromedp.Flag("metrics-recording-only", arg.MetricsRecordingOnly), + chromedp.Flag("safebrowsing-disable-auto-update", arg.SafebrowsingDisableAutoUpdate), + chromedp.Flag("enable-automation", arg.EnableAutomation), + chromedp.Flag("password-store", arg.PasswordStore), + chromedp.Flag("use-mock-keychain", arg.UseMockKeychain), + }...) + if arg.UserDataDir != "" { + b.eOpts = append(b.eOpts, chromedp.Flag("user-data-dir", arg.UserDataDir)) + } + if arg.ProxyServer != "" { + b.eOpts = append(b.eOpts, chromedp.Flag("proxy-server", arg.ProxyServer)) + } + if arg.WindowSize.Width > 0 && arg.WindowSize.Height > 0 { + b.eOpts = append(b.eOpts, chromedp.Flag("window-size", arg.WindowSize)) + } + if arg.UserAgent != "" { + b.eOpts = append(b.eOpts, chromedp.Flag("user-agent", arg.UserAgent)) + } + return b +} + +// WithExecAllocatorOption sets options. +// Generally unused. +func (b *Builder) WithExecAllocatorOption(opts ...chromedp.ExecAllocatorOption) *Builder { + b.eOpts = append(b.eOpts, opts...) + return b +} + +// WithBrowserOption sets options. +// Generally unused. +func (b *Builder) WithBrowserOption(opts ...chromedp.BrowserOption) *Builder { + b.bOpts = append(b.bOpts, opts...) + return b +} + +// WithContextOption sets options. +// Generally unused. +func (b *Builder) WithContextOption(opts ...chromedp.ContextOption) *Builder { + b.cOpts = append(b.cOpts, opts...) + return b +} + +// WithDeadline sets the deadline. +// Generally unused. +func (b *Builder) WithDeadline(d time.Time) *Builder { + b.deadline = &d + return b +} + +// NewChrome creates a Chrome instance. +func (b *Builder) NewChrome() *Chrome { + NewWithOptions := func( + deadline *time.Time, + eOpts []chromedp.ExecAllocatorOption, + bOpts []chromedp.BrowserOption, + cOpts []chromedp.ContextOption, + ) *Chrome { + if eOpts == nil { + eOpts = []chromedp.ExecAllocatorOption{} + } + if bOpts == nil { + bOpts = []chromedp.BrowserOption{} + } + if cOpts == nil { + cOpts = []chromedp.ContextOption{} + } + baseCtx, baseCancel := context.Background(), context.CancelFunc(nil) + if deadline != nil { + baseCtx, baseCancel = context.WithDeadline(baseCtx, *deadline) + } + exeCtx, exeCancel := chromedp.NewExecAllocator(baseCtx, eOpts...) + tabCtx, tabCancel := chromedp.NewContext(exeCtx, append(cOpts[:], chromedp.WithBrowserOption(bOpts...))...) + chromedp.Run(tabCtx) // ignore error + ret := &Chrome{ + finMu: sync.Mutex{}, + fin: make(chan struct{}), + exeCancel: exeCancel, + tabMu: sync.Mutex{}, + tabs: []*Tab{newMainTab(tabCtx, tabCancel)}, + } + go func() { + <-tabCtx.Done() // when the main tab is dead + defer func() { // DCL + ret.finMu.Lock() + defer ret.finMu.Unlock() + select { + case <-ret.fin: + return + default: + ret.exeCancel() + if baseCancel != nil { // if with deadline + baseCancel() // free all contexts + } + close(ret.fin) + } + }() + }() + return ret + } + return NewWithOptions(b.deadline, b.eOpts, b.bOpts, b.cOpts) +} diff --git a/builder_test.go b/builder_test.go new file mode 100644 index 0000000..0ca6d3d --- /dev/null +++ b/builder_test.go @@ -0,0 +1,42 @@ +package chromebot_test + +import ( + "testing" + "time" + + "github.com/chromedp/chromedp" + "github.com/nanitefactory/chromebot" +) + +func TestBuilder(t *testing.T) { + c := chromebot.NewBuilder(). + WithFlags(chromebot.DefaultBuilderFlags). + WithExecAllocatorOption( + chromedp.DisableGPU, + chromedp.Flag("headless", false), + ). + WithBrowserOption(). + WithContextOption(). + NewChrome() + defer c.Close() + c.AddNewTab() + c.AddNewTab() + time.Sleep(time.Second * 1) +} + +func TestBuilderDeadline(t *testing.T) { + c := chromebot.NewBuilder().WithFlags(func() chromebot.BuilderFlags { + optFlags := chromebot.DefaultBuilderFlags + optFlags.Headless = false + optFlags.MuteAudio = false + optFlags.HideScrollbars = false + return optFlags + }()).WithDeadline(time.Now().Add(time.Second * 3)).NewChrome() + c.AddNewTab() + c.AddNewTab() + c.AddNewTab() + <-c.Dead() + if nTabs := c.CountTabs(); nTabs != 4 { + panic(nTabs) + } +} diff --git a/chrome.go b/chrome.go new file mode 100644 index 0000000..2552a75 --- /dev/null +++ b/chrome.go @@ -0,0 +1,160 @@ +package chromebot + +import ( + "context" + "errors" + "sync" + + "github.com/chromedp/chromedp" +) + +// Chrome represents a running Chrome browser. +type Chrome struct { + finMu sync.Mutex + fin chan struct{} + exeCancel context.CancelFunc + tabMu sync.Mutex + tabs []*Tab // tab id ascending +} + +// New is an alias for NewChrome. +func New(headless bool) *Chrome { + return NewChrome(headless) +} + +// NewChrome runs a new browser. +// Use `(*Chrome).Close()` to free the browser allocated by this. +func NewChrome(headless bool) *Chrome { + exeCtx, exeCancel := chromedp.NewExecAllocator(context.Background(), + func() []chromedp.ExecAllocatorOption { + if headless { + return append(chromedp.DefaultExecAllocatorOptions[:], chromedp.Headless) + } + return append(chromedp.DefaultExecAllocatorOptions[:], + chromedp.Flag("headless", false), + chromedp.Flag("hide-scrollbars", false), + chromedp.Flag("mute-audio", false), + ) // windowed foreground + }()...) + tabCtx, tabCancel := chromedp.NewContext(exeCtx) + chromedp.Run(tabCtx) // ignore error + ret := &Chrome{ + finMu: sync.Mutex{}, + fin: make(chan struct{}), + exeCancel: exeCancel, + tabMu: sync.Mutex{}, + tabs: []*Tab{newMainTab(tabCtx, tabCancel)}, + } + go func() { + <-tabCtx.Done() // when the main tab is dead + defer func() { // DCL + ret.finMu.Lock() + defer ret.finMu.Unlock() + select { + case <-ret.fin: + return + default: // free + ret.exeCancel() + close(ret.fin) + } + }() + }() + return ret +} + +// Close gracefully closes the browser and all its tabs. +func (c *Chrome) Close() { + defer func() { // DCL + c.finMu.Lock() + defer c.finMu.Unlock() + select { + case <-c.fin: + return + default: + c.exeCancel() + close(c.fin) + } + }() +} + +// Dead returns a channel that's closed when work done on behalf of the browser should be dead. +// This notifies a user when this browser is closed. +func (c *Chrome) Dead() <-chan struct{} { + return c.fin +} + +// Do runs a cdproto command on this browser. +// You might consider using `(*Tab).Do()` instead, as this function cannot run page specific methods like `Page.navigate()`. +// func (c *Chrome) Do() domain.Domain { +// ctx := func() context.Context { +// c.tabMu.Lock() +// defer c.tabMu.Unlock() +// return c.tabs[0].ctx +// }() +// return domain.Do(cdp.WithExecutor(ctx, chromedp.FromContext(ctx).Browser)) +// } + +// Listen adds a callback function which will be called whenever a browser event is received on this browser. +// +// Usage: +// c.Listen(func(ev interface{}) { +// switch ev := ev.(type) { +// case *runtime.EventConsoleAPICalled: +// // do something with ev +// case *runtime.EventExceptionThrown: +// // do something with ev +// } +// }) +// +// Note that the function is called synchronously when handling events. +// The function should avoid blocking at all costs. +// For example, any Actions must be run via a separate goroutine. +func (c *Chrome) Listen(fn func(ev interface{})) error { + select { + case <-c.fin: + return errors.New("the browser is dead") + default: + } + c.tabMu.Lock() + defer c.tabMu.Unlock() + chromedp.ListenBrowser(c.tabs[0].ctx, fn) + return nil +} + +// CountTabs returns the number of tabs created by this Chrome. +func (c *Chrome) CountTabs() int { + c.tabMu.Lock() + defer c.tabMu.Unlock() + return len(c.tabs) +} + +// AddNewTab creates a new tab and add it to this Chrome. +// The function returns `nil` when the browser is dead. +// Panic if `chromedp.WithBrowserOption()` passed as an argument. +// Only tab options are accepted. +func (c *Chrome) AddNewTab(opts ...chromedp.ContextOption) (added *Tab) { + select { + case <-c.fin: + return nil + default: + } + c.tabMu.Lock() + defer c.tabMu.Unlock() + ctx, cancel := chromedp.NewContext(c.tabs[0].ctx, opts...) + retTab := newExtraTab(ctx, cancel) + c.tabs = append(c.tabs, retTab) + chromedp.Run(retTab.ctx) + return retTab +} + +// Tab is a getter retrieving a tab. Returns nil upon exception. +// The `indexOfTab` is an integer within [0, N) where N is the number of tabs created by the browser. +// E.g. `(*Chrome).Tab(0)` will return the first tab of the browser. Tab(1) for the second one, Tab(2) for the third one and so on. +func (c *Chrome) Tab(indexOfTab int) *Tab { + c.tabMu.Lock() + defer c.tabMu.Unlock() + if indexOfTab >= len(c.tabs) || indexOfTab < 0 { + return nil + } + return c.tabs[indexOfTab] +} diff --git a/chrome_test.go b/chrome_test.go new file mode 100644 index 0000000..690175e --- /dev/null +++ b/chrome_test.go @@ -0,0 +1,113 @@ +package chromebot_test + +import ( + "context" + "log" + "testing" + "time" + + "github.com/chromedp/chromedp" + "github.com/nanitefactory/chromebot" +) + +func TestChromedp(t *testing.T) { + ctx, cancel := chromedp.NewExecAllocator(context.Background(), chromedp.Headless) + defer cancel() + ctx2, _ := chromedp.NewContext(ctx) + chromedp.Run(ctx2) +} + +func TestNewChrome(t *testing.T) { + chromebot.New(false).Close() + chromebot.New(true).Close() +} + +func TestChromeManyTabs(t *testing.T) { + testCountTab := func(c *chromebot.Chrome, n int) { + if c.CountTabs() != n { + panic("c.CountTabs() not working well") + } + } + c := chromebot.New(false) + defer c.Close() + // + n := 1 + testCountTab(c, n) + // + tab1 := c.AddNewTab() + n++ + testCountTab(c, n) + // + tab2 := c.AddNewTab() + n++ + testCountTab(c, n) + // + for i := 0; i < 10; i++ { + c.AddNewTab() + n++ + testCountTab(c, n) + } + // + tab2.Close() + tab1.Close() + for i := 0; i < c.CountTabs(); i++ { + c.Tab(i).Close() + time.Sleep(time.Millisecond * 100) + } + testCountTab(c, n) +} + +func TestChromeClose(t *testing.T) { + c1 := chromebot.New(false) + defer c1.Close() + defer c1.Close() + defer c1.Close() + c1.AddNewTab() + c1.Tab(0).Close() + c1.Tab(0).Close() + c1.Tab(0).Close() + c1.AddNewTab() +} + +func TestChromeTabAsBrowser(t *testing.T) { + defer func() { // expecting a panic + if r := recover(); r == nil { + panic("must panic but it didn't panic") + } + }() + c := chromebot.New(false) + defer c.Close() + c.AddNewTab(chromedp.WithBrowserOption(chromedp.WithBrowserLogf(func(str string, args ...interface{}) { + log.Println() + }))) +} + +func TestDeadChrome(t *testing.T) { + c := chromebot.New(false) + deadTab := c.Tab(0) + c.Close() + c.Close() + c.Close() + c.Close() + if tab := c.Tab(0); tab == nil { + panic(tab) + } + if nTabs := c.CountTabs(); nTabs != 1 { + panic(nTabs) + } + c.Tab(0).Close() + if c.Tab(0) != deadTab { + panic("failed to get the first tab") + } + if tab := c.AddNewTab(); tab != nil { + panic(tab) + } + if err := c.Listen(func(ev interface{}) {}); err == nil { + panic("Listen() should error") + } + select { + case <-c.Dead(): + default: + panic("Dead() not working well") + } +} diff --git a/doc.go b/doc.go new file mode 100644 index 0000000..65e3a0e --- /dev/null +++ b/doc.go @@ -0,0 +1,4 @@ +/* +Package chromebot simplifies driving browsers based on chromedp. +*/ +package chromebot diff --git a/domain/accessibility.go b/domain/accessibility.go new file mode 100644 index 0000000..bd57ddc --- /dev/null +++ b/domain/accessibility.go @@ -0,0 +1,75 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/accessibility" + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/runtime" +) + +// Accessibility executes a cdproto command under Accessibility domain. +type Accessibility struct { + ctxWithExecutor context.Context +} + +// Disable disables the accessibility domain. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-disable +func (doAccessibility Accessibility) Disable() (err error) { + b := accessibility.Disable() + return b.Do(doAccessibility.ctxWithExecutor) +} + +// Enable enables the accessibility domain which causes AXNodeIds to remain +// consistent between method calls. This turns on accessibility for the page, +// which can impact performance until accessibility is disabled. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-enable +func (doAccessibility Accessibility) Enable() (err error) { + b := accessibility.Enable() + return b.Do(doAccessibility.ctxWithExecutor) +} + +// GetPartialAXTree fetches the accessibility node and partial accessibility +// tree for this DOM node, if it exists. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getPartialAXTree +// +// parameters: +// - `nodeID`: This can be nil. (Optional) Identifier of the node to get the partial accessibility tree for. +// - `backendNodeID`: This can be nil. (Optional) Identifier of the backend node to get the partial accessibility tree for. +// - `objectID`: This can be nil. (Optional) JavaScript object id of the node wrapper to get the partial accessibility tree for. +// - `fetchRelatives`: This can be nil. (Optional) Whether to fetch this nodes ancestors, siblings and children. Defaults to true. +// +// returns: +// - `retNodes`: The Accessibility.AXNode for this DOM node, if it exists, plus its ancestors, siblings and children, if requested. +func (doAccessibility Accessibility) GetPartialAXTree(nodeID *cdp.NodeID, backendNodeID *cdp.BackendNodeID, objectID *runtime.RemoteObjectID, fetchRelatives *bool) (retNodes []*accessibility.Node, err error) { + b := accessibility.GetPartialAXTree() + if nodeID != nil { + b = b.WithNodeID(*nodeID) + } + if backendNodeID != nil { + b = b.WithBackendNodeID(*backendNodeID) + } + if objectID != nil { + b = b.WithObjectID(*objectID) + } + if fetchRelatives != nil { + b = b.WithFetchRelatives(*fetchRelatives) + } + return b.Do(doAccessibility.ctxWithExecutor) +} + +// GetFullAXTree fetches the entire accessibility tree. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#method-getFullAXTree +// +// returns: +// - `retNodes` +func (doAccessibility Accessibility) GetFullAXTree() (retNodes []*accessibility.Node, err error) { + b := accessibility.GetFullAXTree() + return b.Do(doAccessibility.ctxWithExecutor) +} diff --git a/domain/animation.go b/domain/animation.go new file mode 100644 index 0000000..431a77a --- /dev/null +++ b/domain/animation.go @@ -0,0 +1,131 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/animation" + "github.com/chromedp/cdproto/runtime" +) + +// Animation executes a cdproto command under Animation domain. +type Animation struct { + ctxWithExecutor context.Context +} + +// Disable disables animation domain notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-disable +func (doAnimation Animation) Disable() (err error) { + b := animation.Disable() + return b.Do(doAnimation.ctxWithExecutor) +} + +// Enable enables animation domain notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-enable +func (doAnimation Animation) Enable() (err error) { + b := animation.Enable() + return b.Do(doAnimation.ctxWithExecutor) +} + +// GetCurrentTime returns the current time of the an animation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-getCurrentTime +// +// parameters: +// - `id`: Id of animation. +// +// returns: +// - `retCurrentTime`: Current time of the page. +func (doAnimation Animation) GetCurrentTime(id string) (retCurrentTime float64, err error) { + b := animation.GetCurrentTime(id) + return b.Do(doAnimation.ctxWithExecutor) +} + +// GetPlaybackRate gets the playback rate of the document timeline. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-getPlaybackRate +// +// returns: +// - `retPlaybackRate`: Playback rate for animations on page. +func (doAnimation Animation) GetPlaybackRate() (retPlaybackRate float64, err error) { + b := animation.GetPlaybackRate() + return b.Do(doAnimation.ctxWithExecutor) +} + +// ReleaseAnimations releases a set of animations to no longer be +// manipulated. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-releaseAnimations +// +// parameters: +// - `animations`: List of animation ids to seek. +func (doAnimation Animation) ReleaseAnimations(animations []string) (err error) { + b := animation.ReleaseAnimations(animations) + return b.Do(doAnimation.ctxWithExecutor) +} + +// ResolveAnimation gets the remote object of the Animation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-resolveAnimation +// +// parameters: +// - `animationID`: Animation id. +// +// returns: +// - `retRemoteObject`: Corresponding remote object. +func (doAnimation Animation) ResolveAnimation(animationID string) (retRemoteObject *runtime.RemoteObject, err error) { + b := animation.ResolveAnimation(animationID) + return b.Do(doAnimation.ctxWithExecutor) +} + +// SeekAnimations seek a set of animations to a particular time within each +// animation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-seekAnimations +// +// parameters: +// - `animations`: List of animation ids to seek. +// - `currentTime`: Set the current time of each animation. +func (doAnimation Animation) SeekAnimations(animations []string, currentTime float64) (err error) { + b := animation.SeekAnimations(animations, currentTime) + return b.Do(doAnimation.ctxWithExecutor) +} + +// SetPaused sets the paused state of a set of animations. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-setPaused +// +// parameters: +// - `animations`: Animations to set the pause state of. +// - `paused`: Paused state to set to. +func (doAnimation Animation) SetPaused(animations []string, paused bool) (err error) { + b := animation.SetPaused(animations, paused) + return b.Do(doAnimation.ctxWithExecutor) +} + +// SetPlaybackRate sets the playback rate of the document timeline. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-setPlaybackRate +// +// parameters: +// - `playbackRate`: Playback rate for animations on page +func (doAnimation Animation) SetPlaybackRate(playbackRate float64) (err error) { + b := animation.SetPlaybackRate(playbackRate) + return b.Do(doAnimation.ctxWithExecutor) +} + +// SetTiming sets the timing of an animation node. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Animation#method-setTiming +// +// parameters: +// - `animationID`: Animation id. +// - `duration`: Duration of the animation. +// - `delay`: Delay of the animation. +func (doAnimation Animation) SetTiming(animationID string, duration float64, delay float64) (err error) { + b := animation.SetTiming(animationID, duration, delay) + return b.Do(doAnimation.ctxWithExecutor) +} diff --git a/domain/applicationcache.go b/domain/applicationcache.go new file mode 100644 index 0000000..68c0632 --- /dev/null +++ b/domain/applicationcache.go @@ -0,0 +1,65 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/applicationcache" + "github.com/chromedp/cdproto/cdp" +) + +// ApplicationCache executes a cdproto command under ApplicationCache domain. +type ApplicationCache struct { + ctxWithExecutor context.Context +} + +// Enable enables application cache domain notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ApplicationCache#method-enable +func (doApplicationCache ApplicationCache) Enable() (err error) { + b := applicationcache.Enable() + return b.Do(doApplicationCache.ctxWithExecutor) +} + +// GetApplicationCacheForFrame returns relevant application cache data for +// the document in given frame. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ApplicationCache#method-getApplicationCacheForFrame +// +// parameters: +// - `frameID`: Identifier of the frame containing document whose application cache is retrieved. +// +// returns: +// - `retApplicationCache`: Relevant application cache data for the document in given frame. +func (doApplicationCache ApplicationCache) GetApplicationCacheForFrame(frameID cdp.FrameID) (retApplicationCache *applicationcache.ApplicationCache, err error) { + b := applicationcache.GetApplicationCacheForFrame(frameID) + return b.Do(doApplicationCache.ctxWithExecutor) +} + +// GetFramesWithManifests returns array of frame identifiers with manifest +// urls for each frame containing a document associated with some application +// cache. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ApplicationCache#method-getFramesWithManifests +// +// returns: +// - `retFrameIds`: Array of frame identifiers with manifest urls for each frame containing a document associated with some application cache. +func (doApplicationCache ApplicationCache) GetFramesWithManifests() (retFrameIds []*applicationcache.FrameWithManifest, err error) { + b := applicationcache.GetFramesWithManifests() + return b.Do(doApplicationCache.ctxWithExecutor) +} + +// GetManifestForFrame returns manifest URL for document in the given frame. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ApplicationCache#method-getManifestForFrame +// +// parameters: +// - `frameID`: Identifier of the frame containing document whose manifest is retrieved. +// +// returns: +// - `retManifestURL`: Manifest URL for document in the given frame. +func (doApplicationCache ApplicationCache) GetManifestForFrame(frameID cdp.FrameID) (retManifestURL string, err error) { + b := applicationcache.GetManifestForFrame(frameID) + return b.Do(doApplicationCache.ctxWithExecutor) +} diff --git a/domain/audits.go b/domain/audits.go new file mode 100644 index 0000000..07fb890 --- /dev/null +++ b/domain/audits.go @@ -0,0 +1,41 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/audits" + "github.com/chromedp/cdproto/network" +) + +// Audits executes a cdproto command under Audits domain. +type Audits struct { + ctxWithExecutor context.Context +} + +// GetEncodedResponse returns the response body and size if it were +// re-encoded with the specified settings. Only applies to images. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Audits#method-getEncodedResponse +// +// parameters: +// - `requestID`: Identifier of the network request to get content for. +// - `encoding`: The encoding to use. +// - `quality`: This can be nil. (Optional) The quality of the encoding (0-1). (defaults to 1) +// - `sizeOnly`: This can be nil. (Optional) Whether to only return the size information (defaults to false). +// +// returns: +// - `retBody`: The encoded body as a base64 string. Omitted if sizeOnly is true. +// - `retOriginalSize`: Size before re-encoding. +// - `retEncodedSize`: Size after re-encoding. +func (doAudits Audits) GetEncodedResponse(requestID network.RequestID, encoding audits.GetEncodedResponseEncoding, quality *float64, sizeOnly *bool) (retBody []byte, retOriginalSize int64, retEncodedSize int64, err error) { + b := audits.GetEncodedResponse(requestID, encoding) + if quality != nil { + b = b.WithQuality(*quality) + } + if sizeOnly != nil { + b = b.WithSizeOnly(*sizeOnly) + } + return b.Do(doAudits.ctxWithExecutor) +} diff --git a/domain/backgroundservice.go b/domain/backgroundservice.go new file mode 100644 index 0000000..e0b9ad4 --- /dev/null +++ b/domain/backgroundservice.go @@ -0,0 +1,59 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/backgroundservice" +) + +// BackgroundService executes a cdproto command under BackgroundService domain. +type BackgroundService struct { + ctxWithExecutor context.Context +} + +// StartObserving enables event updates for the service. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#method-startObserving +// +// parameters: +// - `service` +func (doBackgroundService BackgroundService) StartObserving(service backgroundservice.ServiceName) (err error) { + b := backgroundservice.StartObserving(service) + return b.Do(doBackgroundService.ctxWithExecutor) +} + +// StopObserving disables event updates for the service. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#method-stopObserving +// +// parameters: +// - `service` +func (doBackgroundService BackgroundService) StopObserving(service backgroundservice.ServiceName) (err error) { + b := backgroundservice.StopObserving(service) + return b.Do(doBackgroundService.ctxWithExecutor) +} + +// SetRecording set the recording state for the service. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#method-setRecording +// +// parameters: +// - `shouldRecord` +// - `service` +func (doBackgroundService BackgroundService) SetRecording(shouldRecord bool, service backgroundservice.ServiceName) (err error) { + b := backgroundservice.SetRecording(shouldRecord, service) + return b.Do(doBackgroundService.ctxWithExecutor) +} + +// ClearEvents clears all stored data for the service. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/BackgroundService#method-clearEvents +// +// parameters: +// - `service` +func (doBackgroundService BackgroundService) ClearEvents(service backgroundservice.ServiceName) (err error) { + b := backgroundservice.ClearEvents(service) + return b.Do(doBackgroundService.ctxWithExecutor) +} diff --git a/domain/browser.go b/domain/browser.go new file mode 100644 index 0000000..800aa39 --- /dev/null +++ b/domain/browser.go @@ -0,0 +1,216 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/browser" + "github.com/chromedp/cdproto/target" +) + +// Browser executes a cdproto command under Browser domain. +type Browser struct { + ctxWithExecutor context.Context +} + +// SetPermission set permission settings for given origin. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-setPermission +// +// parameters: +// - `origin`: Origin the permission applies to. +// - `permission`: Descriptor of permission to override. +// - `setting`: Setting of the permission. +// - `browserContextID`: This can be nil. (Optional) Context to override. When omitted, default browser context is used. +func (doBrowser Browser) SetPermission(origin string, permission *browser.PermissionDescriptor, setting browser.PermissionSetting, browserContextID *target.ID) (err error) { + b := browser.SetPermission(origin, permission, setting) + if browserContextID != nil { + b = b.WithBrowserContextID(*browserContextID) + } + return b.Do(doBrowser.ctxWithExecutor) +} + +// GrantPermissions grant specific permissions to the given origin and reject +// all others. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-grantPermissions +// +// parameters: +// - `origin` +// - `permissions` +// - `browserContextID`: This can be nil. (Optional) BrowserContext to override permissions. When omitted, default browser context is used. +func (doBrowser Browser) GrantPermissions(origin string, permissions []browser.PermissionType, browserContextID *target.BrowserContextID) (err error) { + b := browser.GrantPermissions(origin, permissions) + if browserContextID != nil { + b = b.WithBrowserContextID(*browserContextID) + } + return b.Do(doBrowser.ctxWithExecutor) +} + +// ResetPermissions reset all permission management for all origins. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-resetPermissions +// +// parameters: +// - `browserContextID`: This can be nil. (Optional) BrowserContext to reset permissions. When omitted, default browser context is used. +func (doBrowser Browser) ResetPermissions(browserContextID *target.BrowserContextID) (err error) { + b := browser.ResetPermissions() + if browserContextID != nil { + b = b.WithBrowserContextID(*browserContextID) + } + return b.Do(doBrowser.ctxWithExecutor) +} + +// Close close browser gracefully. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-close +func (doBrowser Browser) Close() (err error) { + b := browser.Close() + return b.Do(doBrowser.ctxWithExecutor) +} + +// Crash crashes browser on the main thread. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-crash +func (doBrowser Browser) Crash() (err error) { + b := browser.Crash() + return b.Do(doBrowser.ctxWithExecutor) +} + +// CrashGpuProcess crashes GPU process. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-crashGpuProcess +func (doBrowser Browser) CrashGpuProcess() (err error) { + b := browser.CrashGpuProcess() + return b.Do(doBrowser.ctxWithExecutor) +} + +// GetVersion returns version information. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getVersion +// +// returns: +// - `retProtocolVersion`: Protocol version. +// - `retProduct`: Product name. +// - `retRevision`: Product revision. +// - `retUserAgent`: User-Agent. +// - `retJsVersion`: V8 version. +func (doBrowser Browser) GetVersion() (retProtocolVersion string, retProduct string, retRevision string, retUserAgent string, retJsVersion string, err error) { + b := browser.GetVersion() + return b.Do(doBrowser.ctxWithExecutor) +} + +// GetBrowserCommandLine returns the command line switches for the browser +// process if, and only if --enable-automation is on the commandline. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getBrowserCommandLine +// +// returns: +// - `retArguments`: Commandline parameters +func (doBrowser Browser) GetBrowserCommandLine() (retArguments []string, err error) { + b := browser.GetBrowserCommandLine() + return b.Do(doBrowser.ctxWithExecutor) +} + +// GetHistograms get Chrome histograms. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getHistograms +// +// parameters: +// - `query`: This can be nil. (Optional) Requested substring in name. Only histograms which have query as a substring in their name are extracted. An empty or absent query returns all histograms. +// - `delta`: This can be nil. (Optional) If true, retrieve delta since last call. +// +// returns: +// - `retHistograms`: Histograms. +func (doBrowser Browser) GetHistograms(query *string, delta *bool) (retHistograms []*browser.Histogram, err error) { + b := browser.GetHistograms() + if query != nil { + b = b.WithQuery(*query) + } + if delta != nil { + b = b.WithDelta(*delta) + } + return b.Do(doBrowser.ctxWithExecutor) +} + +// GetHistogram get a Chrome histogram by name. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getHistogram +// +// parameters: +// - `name`: Requested histogram name. +// - `delta`: This can be nil. (Optional) If true, retrieve delta since last call. +// +// returns: +// - `retHistogram`: Histogram. +func (doBrowser Browser) GetHistogram(name string, delta *bool) (retHistogram *browser.Histogram, err error) { + b := browser.GetHistogram(name) + if delta != nil { + b = b.WithDelta(*delta) + } + return b.Do(doBrowser.ctxWithExecutor) +} + +// GetWindowBounds get position and size of the browser window. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getWindowBounds +// +// parameters: +// - `windowID`: Browser window id. +// +// returns: +// - `retBounds`: Bounds information of the window. When window state is 'minimized', the restored window position and size are returned. +func (doBrowser Browser) GetWindowBounds(windowID browser.WindowID) (retBounds *browser.Bounds, err error) { + b := browser.GetWindowBounds(windowID) + return b.Do(doBrowser.ctxWithExecutor) +} + +// GetWindowForTarget get the browser window that contains the devtools +// target. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-getWindowForTarget +// +// parameters: +// - `targetID`: This can be nil. (Optional) Devtools agent host id. If called as a part of the session, associated targetId is used. +// +// returns: +// - `retWindowID`: Browser window id. +// - `retBounds`: Bounds information of the window. When window state is 'minimized', the restored window position and size are returned. +func (doBrowser Browser) GetWindowForTarget(targetID *target.ID) (retWindowID browser.WindowID, retBounds *browser.Bounds, err error) { + b := browser.GetWindowForTarget() + if targetID != nil { + b = b.WithTargetID(*targetID) + } + return b.Do(doBrowser.ctxWithExecutor) +} + +// SetWindowBounds set position and/or size of the browser window. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-setWindowBounds +// +// parameters: +// - `windowID`: Browser window id. +// - `bounds`: New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged. +func (doBrowser Browser) SetWindowBounds(windowID browser.WindowID, bounds *browser.Bounds) (err error) { + b := browser.SetWindowBounds(windowID, bounds) + return b.Do(doBrowser.ctxWithExecutor) +} + +// SetDockTile set dock tile details, platform-specific. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#method-setDockTile +// +// parameters: +// - `badgeLabel` +// - `image`: This can be nil. (Optional) Png encoded image. +func (doBrowser Browser) SetDockTile(badgeLabel *string, image *string) (err error) { + b := browser.SetDockTile() + if badgeLabel != nil { + b = b.WithBadgeLabel(*badgeLabel) + } + if image != nil { + b = b.WithImage(*image) + } + return b.Do(doBrowser.ctxWithExecutor) +} diff --git a/domain/cachestorage.go b/domain/cachestorage.go new file mode 100644 index 0000000..43e9901 --- /dev/null +++ b/domain/cachestorage.go @@ -0,0 +1,88 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/cachestorage" +) + +// CacheStorage executes a cdproto command under CacheStorage domain. +type CacheStorage struct { + ctxWithExecutor context.Context +} + +// DeleteCache deletes a cache. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-deleteCache +// +// parameters: +// - `cacheID`: Id of cache for deletion. +func (doCacheStorage CacheStorage) DeleteCache(cacheID cachestorage.CacheID) (err error) { + b := cachestorage.DeleteCache(cacheID) + return b.Do(doCacheStorage.ctxWithExecutor) +} + +// DeleteEntry deletes a cache entry. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-deleteEntry +// +// parameters: +// - `cacheID`: Id of cache where the entry will be deleted. +// - `request`: URL spec of the request. +func (doCacheStorage CacheStorage) DeleteEntry(cacheID cachestorage.CacheID, request string) (err error) { + b := cachestorage.DeleteEntry(cacheID, request) + return b.Do(doCacheStorage.ctxWithExecutor) +} + +// RequestCacheNames requests cache names. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCacheNames +// +// parameters: +// - `securityOrigin`: Security origin. +// +// returns: +// - `retCaches`: Caches for the security origin. +func (doCacheStorage CacheStorage) RequestCacheNames(securityOrigin string) (retCaches []*cachestorage.Cache, err error) { + b := cachestorage.RequestCacheNames(securityOrigin) + return b.Do(doCacheStorage.ctxWithExecutor) +} + +// RequestCachedResponse fetches cache entry. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestCachedResponse +// +// parameters: +// - `cacheID`: Id of cache that contains the entry. +// - `requestURL`: URL spec of the request. +// - `requestHeaders`: headers of the request. +// +// returns: +// - `retResponse`: Response read from the cache. +func (doCacheStorage CacheStorage) RequestCachedResponse(cacheID cachestorage.CacheID, requestURL string, requestHeaders []*cachestorage.Header) (retResponse *cachestorage.CachedResponse, err error) { + b := cachestorage.RequestCachedResponse(cacheID, requestURL, requestHeaders) + return b.Do(doCacheStorage.ctxWithExecutor) +} + +// RequestEntries requests data from cache. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CacheStorage#method-requestEntries +// +// parameters: +// - `cacheID`: ID of cache to get entries from. +// - `skipCount`: This can be nil. (Optional) Number of records to skip. +// - `pageSize`: This can be nil. (Optional) Number of records to fetch. +// - `pathFilter`: This can be nil. (Optional) If present, only return the entries containing this substring in the path +// +// returns: +// - `retCacheDataEntries`: Array of object store data entries. +// - `retReturnCount`: Count of returned entries from this storage. If pathFilter is empty, it is the count of all entries from this storage. +func (doCacheStorage CacheStorage) RequestEntries(cacheID cachestorage.CacheID, skipCount *int64, pageSize *int64, pathFilter *string) (retCacheDataEntries []*cachestorage.DataEntry, retReturnCount float64, err error) { + b := cachestorage.RequestEntries(cacheID) + if pathFilter != nil { + b = b.WithPathFilter(*pathFilter) + } + return b.Do(doCacheStorage.ctxWithExecutor) +} diff --git a/domain/cast.go b/domain/cast.go new file mode 100644 index 0000000..aa5a5f5 --- /dev/null +++ b/domain/cast.go @@ -0,0 +1,74 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/cast" +) + +// Cast executes a cdproto command under Cast domain. +type Cast struct { + ctxWithExecutor context.Context +} + +// Enable starts observing for sinks that can be used for tab mirroring, and +// if set, sinks compatible with |presentationUrl| as well. When sinks are +// found, a |sinksUpdated| event is fired. Also starts observing for issue +// messages. When an issue is added or removed, an |issueUpdated| event is +// fired. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-enable +// +// parameters: +// - `presentationURL` +func (doCast Cast) Enable(presentationURL *string) (err error) { + b := cast.Enable() + if presentationURL != nil { + b = b.WithPresentationURL(*presentationURL) + } + return b.Do(doCast.ctxWithExecutor) +} + +// Disable stops observing for sinks and issues. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-disable +func (doCast Cast) Disable() (err error) { + b := cast.Disable() + return b.Do(doCast.ctxWithExecutor) +} + +// SetSinkToUse sets a sink to be used when the web page requests the browser +// to choose a sink via Presentation API, Remote Playback API, or Cast SDK. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-setSinkToUse +// +// parameters: +// - `sinkName` +func (doCast Cast) SetSinkToUse(sinkName string) (err error) { + b := cast.SetSinkToUse(sinkName) + return b.Do(doCast.ctxWithExecutor) +} + +// StartTabMirroring starts mirroring the tab to the sink. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-startTabMirroring +// +// parameters: +// - `sinkName` +func (doCast Cast) StartTabMirroring(sinkName string) (err error) { + b := cast.StartTabMirroring(sinkName) + return b.Do(doCast.ctxWithExecutor) +} + +// StopCasting stops the active Cast session on the sink. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Cast#method-stopCasting +// +// parameters: +// - `sinkName` +func (doCast Cast) StopCasting(sinkName string) (err error) { + b := cast.StopCasting(sinkName) + return b.Do(doCast.ctxWithExecutor) +} diff --git a/domain/css.go b/domain/css.go new file mode 100644 index 0000000..7ae3fd5 --- /dev/null +++ b/domain/css.go @@ -0,0 +1,325 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/css" +) + +// CSS executes a cdproto command under CSS domain. +type CSS struct { + ctxWithExecutor context.Context +} + +// AddRule inserts a new rule with the given ruleText in a stylesheet with +// given styleSheetId, at the position specified by location. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-addRule +// +// parameters: +// - `styleSheetID`: The css style sheet identifier where a new rule should be inserted. +// - `ruleText`: The text of a new rule. +// - `location`: Text position of a new rule in the target style sheet. +// +// returns: +// - `retRule`: The newly created rule. +func (doCSS CSS) AddRule(styleSheetID css.StyleSheetID, ruleText string, location *css.SourceRange) (retRule *css.Rule, err error) { + b := css.AddRule(styleSheetID, ruleText, location) + return b.Do(doCSS.ctxWithExecutor) +} + +// CollectClassNames returns all class names from specified stylesheet. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-collectClassNames +// +// parameters: +// - `styleSheetID` +// +// returns: +// - `retClassNames`: Class name list. +func (doCSS CSS) CollectClassNames(styleSheetID css.StyleSheetID) (retClassNames []string, err error) { + b := css.CollectClassNames(styleSheetID) + return b.Do(doCSS.ctxWithExecutor) +} + +// CreateStyleSheet creates a new special "via-inspector" stylesheet in the +// frame with given frameId. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-createStyleSheet +// +// parameters: +// - `frameID`: Identifier of the frame where "via-inspector" stylesheet should be created. +// +// returns: +// - `retStyleSheetID`: Identifier of the created "via-inspector" stylesheet. +func (doCSS CSS) CreateStyleSheet(frameID cdp.FrameID) (retStyleSheetID css.StyleSheetID, err error) { + b := css.CreateStyleSheet(frameID) + return b.Do(doCSS.ctxWithExecutor) +} + +// Disable disables the CSS agent for the given page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-disable +func (doCSS CSS) Disable() (err error) { + b := css.Disable() + return b.Do(doCSS.ctxWithExecutor) +} + +// Enable enables the CSS agent for the given page. Clients should not assume +// that the CSS agent has been enabled until the result of this command is +// received. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-enable +func (doCSS CSS) Enable() (err error) { + b := css.Enable() + return b.Do(doCSS.ctxWithExecutor) +} + +// ForcePseudoState ensures that the given node will have specified +// pseudo-classes whenever its style is computed by the browser. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-forcePseudoState +// +// parameters: +// - `nodeID`: The element id for which to force the pseudo state. +// - `forcedPseudoClasses`: Element pseudo classes to force when computing the element's style. +func (doCSS CSS) ForcePseudoState(nodeID cdp.NodeID, forcedPseudoClasses []string) (err error) { + b := css.ForcePseudoState(nodeID, forcedPseudoClasses) + return b.Do(doCSS.ctxWithExecutor) +} + +// GetBackgroundColors [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getBackgroundColors +// +// parameters: +// - `nodeID`: Id of the node to get background colors for. +// +// returns: +// - `retBackgroundColors`: The range of background colors behind this element, if it contains any visible text. If no visible text is present, this will be undefined. In the case of a flat background color, this will consist of simply that color. In the case of a gradient, this will consist of each of the color stops. For anything more complicated, this will be an empty array. Images will be ignored (as if the image had failed to load). +// - `retComputedFontSize`: The computed font size for this node, as a CSS computed value string (e.g. '12px'). +// - `retComputedFontWeight`: The computed font weight for this node, as a CSS computed value string (e.g. 'normal' or '100'). +func (doCSS CSS) GetBackgroundColors(nodeID cdp.NodeID) (retBackgroundColors []string, retComputedFontSize string, retComputedFontWeight string, err error) { + b := css.GetBackgroundColors(nodeID) + return b.Do(doCSS.ctxWithExecutor) +} + +// GetComputedStyleForNode returns the computed style for a DOM node +// identified by nodeId. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getComputedStyleForNode +// +// parameters: +// - `nodeID` +// +// returns: +// - `retComputedStyle`: Computed style for the specified DOM node. +func (doCSS CSS) GetComputedStyleForNode(nodeID cdp.NodeID) (retComputedStyle []*css.ComputedProperty, err error) { + b := css.GetComputedStyleForNode(nodeID) + return b.Do(doCSS.ctxWithExecutor) +} + +// GetInlineStylesForNode returns the styles defined inline (explicitly in +// the "style" attribute and implicitly, using DOM attributes) for a DOM node +// identified by nodeId. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getInlineStylesForNode +// +// parameters: +// - `nodeID` +// +// returns: +// - `retInlineStyle`: Inline style for the specified DOM node. +// - `retAttributesStyle`: Attribute-defined element style (e.g. resulting from "width=20 height=100%"). +func (doCSS CSS) GetInlineStylesForNode(nodeID cdp.NodeID) (retInlineStyle *css.Style, retAttributesStyle *css.Style, err error) { + b := css.GetInlineStylesForNode(nodeID) + return b.Do(doCSS.ctxWithExecutor) +} + +// GetMatchedStylesForNode returns requested styles for a DOM node identified +// by nodeId. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMatchedStylesForNode +// +// parameters: +// - `nodeID` +// +// returns: +// - `retInlineStyle`: Inline style for the specified DOM node. +// - `retAttributesStyle`: Attribute-defined element style (e.g. resulting from "width=20 height=100%"). +// - `retMatchedCSSRules`: CSS rules matching this node, from all applicable stylesheets. +// - `retPseudoElements`: Pseudo style matches for this node. +// - `retInherited`: A chain of inherited styles (from the immediate node parent up to the DOM tree root). +// - `retCSSKeyframesRules`: A list of CSS keyframed animations matching this node. +func (doCSS CSS) GetMatchedStylesForNode(nodeID cdp.NodeID) (retInlineStyle *css.Style, retAttributesStyle *css.Style, retMatchedCSSRules []*css.RuleMatch, retPseudoElements []*css.PseudoElementMatches, retInherited []*css.InheritedStyleEntry, retCSSKeyframesRules []*css.KeyframesRule, err error) { + b := css.GetMatchedStylesForNode(nodeID) + return b.Do(doCSS.ctxWithExecutor) +} + +// GetMediaQueries returns all media queries parsed by the rendering engine. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getMediaQueries +// +// returns: +// - `retMedias` +func (doCSS CSS) GetMediaQueries() (retMedias []*css.Media, err error) { + b := css.GetMediaQueries() + return b.Do(doCSS.ctxWithExecutor) +} + +// GetPlatformFontsForNode requests information about platform fonts which we +// used to render child TextNodes in the given node. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getPlatformFontsForNode +// +// parameters: +// - `nodeID` +// +// returns: +// - `retFonts`: Usage statistics for every employed platform font. +func (doCSS CSS) GetPlatformFontsForNode(nodeID cdp.NodeID) (retFonts []*css.PlatformFontUsage, err error) { + b := css.GetPlatformFontsForNode(nodeID) + return b.Do(doCSS.ctxWithExecutor) +} + +// GetStyleSheetText returns the current textual content for a stylesheet. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-getStyleSheetText +// +// parameters: +// - `styleSheetID` +// +// returns: +// - `retText`: The stylesheet text. +func (doCSS CSS) GetStyleSheetText(styleSheetID css.StyleSheetID) (retText string, err error) { + b := css.GetStyleSheetText(styleSheetID) + return b.Do(doCSS.ctxWithExecutor) +} + +// SetEffectivePropertyValueForNode find a rule with the given active +// property for the given node and set the new value for this property. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setEffectivePropertyValueForNode +// +// parameters: +// - `nodeID`: The element id for which to set property. +// - `propertyName` +// - `value` +func (doCSS CSS) SetEffectivePropertyValueForNode(nodeID cdp.NodeID, propertyName string, value string) (err error) { + b := css.SetEffectivePropertyValueForNode(nodeID, propertyName, value) + return b.Do(doCSS.ctxWithExecutor) +} + +// SetKeyframeKey modifies the keyframe rule key text. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setKeyframeKey +// +// parameters: +// - `styleSheetID` +// - `range` +// - `keyText` +// +// returns: +// - `retKeyText`: The resulting key text after modification. +func (doCSS CSS) SetKeyframeKey(styleSheetID css.StyleSheetID, rangeVal *css.SourceRange, keyText string) (retKeyText *css.Value, err error) { + b := css.SetKeyframeKey(styleSheetID, rangeVal, keyText) + return b.Do(doCSS.ctxWithExecutor) +} + +// SetMediaText modifies the rule selector. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setMediaText +// +// parameters: +// - `styleSheetID` +// - `range` +// - `text` +// +// returns: +// - `retMedia`: The resulting CSS media rule after modification. +func (doCSS CSS) SetMediaText(styleSheetID css.StyleSheetID, rangeVal *css.SourceRange, text string) (retMedia *css.Media, err error) { + b := css.SetMediaText(styleSheetID, rangeVal, text) + return b.Do(doCSS.ctxWithExecutor) +} + +// SetRuleSelector modifies the rule selector. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setRuleSelector +// +// parameters: +// - `styleSheetID` +// - `range` +// - `selector` +// +// returns: +// - `retSelectorList`: The resulting selector list after modification. +func (doCSS CSS) SetRuleSelector(styleSheetID css.StyleSheetID, rangeVal *css.SourceRange, selector string) (retSelectorList *css.SelectorList, err error) { + b := css.SetRuleSelector(styleSheetID, rangeVal, selector) + return b.Do(doCSS.ctxWithExecutor) +} + +// SetStyleSheetText sets the new stylesheet text. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleSheetText +// +// parameters: +// - `styleSheetID` +// - `text` +// +// returns: +// - `retSourceMapURL`: URL of source map associated with script (if any). +func (doCSS CSS) SetStyleSheetText(styleSheetID css.StyleSheetID, text string) (retSourceMapURL string, err error) { + b := css.SetStyleSheetText(styleSheetID, text) + return b.Do(doCSS.ctxWithExecutor) +} + +// SetStyleTexts applies specified style edits one after another in the given +// order. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-setStyleTexts +// +// parameters: +// - `edits` +// +// returns: +// - `retStyles`: The resulting styles after modification. +func (doCSS CSS) SetStyleTexts(edits []*css.StyleDeclarationEdit) (retStyles []*css.Style, err error) { + b := css.SetStyleTexts(edits) + return b.Do(doCSS.ctxWithExecutor) +} + +// StartRuleUsageTracking enables the selector recording. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-startRuleUsageTracking +func (doCSS CSS) StartRuleUsageTracking() (err error) { + b := css.StartRuleUsageTracking() + return b.Do(doCSS.ctxWithExecutor) +} + +// StopRuleUsageTracking stop tracking rule usage and return the list of +// rules that were used since last call to takeCoverageDelta (or since start of +// coverage instrumentation). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-stopRuleUsageTracking +// +// returns: +// - `retRuleUsage` +func (doCSS CSS) StopRuleUsageTracking() (retRuleUsage []*css.RuleUsage, err error) { + b := css.StopRuleUsageTracking() + return b.Do(doCSS.ctxWithExecutor) +} + +// TakeCoverageDelta obtain list of rules that became used since last call to +// this method (or since start of coverage instrumentation). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/CSS#method-takeCoverageDelta +// +// returns: +// - `retCoverage` +func (doCSS CSS) TakeCoverageDelta() (retCoverage []*css.RuleUsage, err error) { + b := css.TakeCoverageDelta() + return b.Do(doCSS.ctxWithExecutor) +} diff --git a/domain/database.go b/domain/database.go new file mode 100644 index 0000000..57fc8af --- /dev/null +++ b/domain/database.go @@ -0,0 +1,64 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/database" + "github.com/mailru/easyjson" +) + +// Database executes a cdproto command under Database domain. +type Database struct { + ctxWithExecutor context.Context +} + +// Disable disables database tracking, prevents database events from being +// sent to the client. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Database#method-disable +func (doDatabase Database) Disable() (err error) { + b := database.Disable() + return b.Do(doDatabase.ctxWithExecutor) +} + +// Enable enables database tracking, database events will now be delivered to +// the client. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Database#method-enable +func (doDatabase Database) Enable() (err error) { + b := database.Enable() + return b.Do(doDatabase.ctxWithExecutor) +} + +// ExecuteSQL [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Database#method-executeSQL +// +// parameters: +// - `databaseID` +// - `query` +// +// returns: +// - `retColumnNames` +// - `retValues` +// - `retSQLError` +func (doDatabase Database) ExecuteSQL(databaseID database.ID, query string) (retColumnNames []string, retValues []easyjson.RawMessage, retSQLError *database.Error, err error) { + b := database.ExecuteSQL(databaseID, query) + return b.Do(doDatabase.ctxWithExecutor) +} + +// GetDatabaseTableNames [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Database#method-getDatabaseTableNames +// +// parameters: +// - `databaseID` +// +// returns: +// - `retTableNames` +func (doDatabase Database) GetDatabaseTableNames(databaseID database.ID) (retTableNames []string, err error) { + b := database.GetDatabaseTableNames(databaseID) + return b.Do(doDatabase.ctxWithExecutor) +} diff --git a/domain/debugger.go b/domain/debugger.go new file mode 100644 index 0000000..2c49768 --- /dev/null +++ b/domain/debugger.go @@ -0,0 +1,480 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/debugger" + "github.com/chromedp/cdproto/runtime" +) + +// Debugger executes a cdproto command under Debugger domain. +type Debugger struct { + ctxWithExecutor context.Context +} + +// ContinueToLocation continues execution until specific location is reached. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-continueToLocation +// +// parameters: +// - `location`: Location to continue to. +// - `targetCallFrames` +func (doDebugger Debugger) ContinueToLocation(location *debugger.Location, targetCallFrames *debugger.ContinueToLocationTargetCallFrames) (err error) { + b := debugger.ContinueToLocation(location) + if targetCallFrames != nil { + b = b.WithTargetCallFrames(*targetCallFrames) + } + return b.Do(doDebugger.ctxWithExecutor) +} + +// Disable disables debugger for given page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-disable +func (doDebugger Debugger) Disable() (err error) { + b := debugger.Disable() + return b.Do(doDebugger.ctxWithExecutor) +} + +// Enable enables debugger for the given page. Clients should not assume that +// the debugging has been enabled until the result for this command is received. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-enable +// +// parameters: +// - `maxScriptsCacheSize`: This can be nil. (Optional) The maximum size in bytes of collected scripts (not referenced by other heap objects) the debugger can hold. Puts no limit if parameter is omitted. +// +// returns: +// - `retDebuggerID`: Unique identifier of the debugger. +func (doDebugger Debugger) Enable(maxScriptsCacheSize *float64) (retDebuggerID runtime.UniqueDebuggerID, err error) { + b := debugger.Enable() + if maxScriptsCacheSize != nil { + b = b.WithMaxScriptsCacheSize(*maxScriptsCacheSize) + } + return b.Do(doDebugger.ctxWithExecutor) +} + +// EvaluateOnCallFrame evaluates expression on a given call frame. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-evaluateOnCallFrame +// +// parameters: +// - `callFrameID`: Call frame identifier to evaluate on. +// - `expression`: Expression to evaluate. +// - `objectGroup`: This can be nil. (Optional) String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). +// - `includeCommandLineAPI`: This can be nil. (Optional) Specifies whether command line API should be available to the evaluated expression, defaults to false. +// - `silent`: This can be nil. (Optional) In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. +// - `returnByValue`: This can be nil. (Optional) Whether the result is expected to be a JSON object that should be sent by value. +// - `generatePreview`: This can be nil. (Optional) Whether preview should be generated for the result. +// - `throwOnSideEffect`: This can be nil. (Optional) Whether to throw an exception if side effect cannot be ruled out during evaluation. +// - `timeout`: This can be nil. (Optional) Terminate execution after timing out (number of milliseconds). +// +// returns: +// - `retResult`: Object wrapper for the evaluation result. +// - `retExceptionDetails`: Exception details. +func (doDebugger Debugger) EvaluateOnCallFrame(callFrameID debugger.CallFrameID, expression string, objectGroup *string, includeCommandLineAPI *bool, silent *bool, returnByValue *bool, generatePreview *bool, throwOnSideEffect *bool, timeout *runtime.TimeDelta) (retResult *runtime.RemoteObject, retExceptionDetails *runtime.ExceptionDetails, err error) { + b := debugger.EvaluateOnCallFrame(callFrameID, expression) + if objectGroup != nil { + b = b.WithObjectGroup(*objectGroup) + } + if includeCommandLineAPI != nil { + b = b.WithIncludeCommandLineAPI(*includeCommandLineAPI) + } + if silent != nil { + b = b.WithSilent(*silent) + } + if returnByValue != nil { + b = b.WithReturnByValue(*returnByValue) + } + if generatePreview != nil { + b = b.WithGeneratePreview(*generatePreview) + } + if throwOnSideEffect != nil { + b = b.WithThrowOnSideEffect(*throwOnSideEffect) + } + if timeout != nil { + b = b.WithTimeout(*timeout) + } + return b.Do(doDebugger.ctxWithExecutor) +} + +// GetPossibleBreakpoints returns possible locations for breakpoint. scriptId +// in start and end range locations should be the same. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-getPossibleBreakpoints +// +// parameters: +// - `start`: Start of range to search possible breakpoint locations in. +// - `end`: This can be nil. (Optional) End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. +// - `restrictToFunction`: This can be nil. (Optional) Only consider locations which are in the same (non-nested) function as start. +// +// returns: +// - `retLocations`: List of the possible breakpoint locations. +func (doDebugger Debugger) GetPossibleBreakpoints(start *debugger.Location, end *debugger.Location, restrictToFunction *bool) (retLocations []*debugger.BreakLocation, err error) { + b := debugger.GetPossibleBreakpoints(start) + if end != nil { + b = b.WithEnd(end) + } + if restrictToFunction != nil { + b = b.WithRestrictToFunction(*restrictToFunction) + } + return b.Do(doDebugger.ctxWithExecutor) +} + +// GetScriptSource returns source for the script with given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-getScriptSource +// +// parameters: +// - `scriptID`: Id of the script to get source for. +// +// returns: +// - `retScriptSource`: Script source. +func (doDebugger Debugger) GetScriptSource(scriptID runtime.ScriptID) (retScriptSource string, err error) { + b := debugger.GetScriptSource(scriptID) + return b.Do(doDebugger.ctxWithExecutor) +} + +// GetWasmBytecode returns bytecode for the WebAssembly script with given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-getWasmBytecode +// +// parameters: +// - `scriptID`: Id of the Wasm script to get source for. +// +// returns: +// - `retBytecode`: Script source. +func (doDebugger Debugger) GetWasmBytecode(scriptID runtime.ScriptID) (retBytecode []byte, err error) { + b := debugger.GetWasmBytecode(scriptID) + return b.Do(doDebugger.ctxWithExecutor) +} + +// GetStackTrace returns stack trace with given stackTraceId. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-getStackTrace +// +// parameters: +// - `stackTraceID` +// +// returns: +// - `retStackTrace` +func (doDebugger Debugger) GetStackTrace(stackTraceID *runtime.StackTraceID) (retStackTrace *runtime.StackTrace, err error) { + b := debugger.GetStackTrace(stackTraceID) + return b.Do(doDebugger.ctxWithExecutor) +} + +// Pause stops on the next JavaScript statement. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-pause +func (doDebugger Debugger) Pause() (err error) { + b := debugger.Pause() + return b.Do(doDebugger.ctxWithExecutor) +} + +// RemoveBreakpoint removes JavaScript breakpoint. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-removeBreakpoint +// +// parameters: +// - `breakpointID` +func (doDebugger Debugger) RemoveBreakpoint(breakpointID debugger.BreakpointID) (err error) { + b := debugger.RemoveBreakpoint(breakpointID) + return b.Do(doDebugger.ctxWithExecutor) +} + +// RestartFrame restarts particular call frame from the beginning. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-restartFrame +// +// parameters: +// - `callFrameID`: Call frame identifier to evaluate on. +// +// returns: +// - `retCallFrames`: New stack trace. +// - `retAsyncStackTrace`: Async stack trace, if any. +// - `retAsyncStackTraceID`: Async stack trace, if any. +func (doDebugger Debugger) RestartFrame(callFrameID debugger.CallFrameID) (retCallFrames []*debugger.CallFrame, retAsyncStackTrace *runtime.StackTrace, retAsyncStackTraceID *runtime.StackTraceID, err error) { + b := debugger.RestartFrame(callFrameID) + return b.Do(doDebugger.ctxWithExecutor) +} + +// Resume resumes JavaScript execution. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-resume +func (doDebugger Debugger) Resume() (err error) { + b := debugger.Resume() + return b.Do(doDebugger.ctxWithExecutor) +} + +// SearchInContent searches for given string in script content. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-searchInContent +// +// parameters: +// - `scriptID`: Id of the script to search in. +// - `query`: String to search for. +// - `caseSensitive`: This can be nil. (Optional) If true, search is case sensitive. +// - `isRegex`: This can be nil. (Optional) If true, treats string parameter as regex. +// +// returns: +// - `retResult`: List of search matches. +func (doDebugger Debugger) SearchInContent(scriptID runtime.ScriptID, query string, caseSensitive *bool, isRegex *bool) (retResult []*debugger.SearchMatch, err error) { + b := debugger.SearchInContent(scriptID, query) + if caseSensitive != nil { + b = b.WithCaseSensitive(*caseSensitive) + } + if isRegex != nil { + b = b.WithIsRegex(*isRegex) + } + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetAsyncCallStackDepth enables or disables async call stacks tracking. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setAsyncCallStackDepth +// +// parameters: +// - `maxDepth`: Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). +func (doDebugger Debugger) SetAsyncCallStackDepth(maxDepth int64) (err error) { + b := debugger.SetAsyncCallStackDepth(maxDepth) + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetBlackboxPatterns replace previous blackbox patterns with passed ones. +// Forces backend to skip stepping/pausing in scripts with url matching one of +// the patterns. VM will try to leave blackboxed script by performing 'step in' +// several times, finally resorting to 'step out' if unsuccessful. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBlackboxPatterns +// +// parameters: +// - `patterns`: Array of regexps that will be used to check script url for blackbox state. +func (doDebugger Debugger) SetBlackboxPatterns(patterns []string) (err error) { + b := debugger.SetBlackboxPatterns(patterns) + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetBlackboxedRanges makes backend skip steps in the script in blackboxed +// ranges. VM will try leave blacklisted scripts by performing 'step in' several +// times, finally resorting to 'step out' if unsuccessful. Positions array +// contains positions where blackbox state is changed. First interval isn't +// blackboxed. Array should be sorted. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBlackboxedRanges +// +// parameters: +// - `scriptID`: Id of the script. +// - `positions` +func (doDebugger Debugger) SetBlackboxedRanges(scriptID runtime.ScriptID, positions []*debugger.ScriptPosition) (err error) { + b := debugger.SetBlackboxedRanges(scriptID, positions) + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetBreakpoint sets JavaScript breakpoint at a given location. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBreakpoint +// +// parameters: +// - `location`: Location to set breakpoint in. +// - `condition`: This can be nil. (Optional) Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. +// +// returns: +// - `retBreakpointID`: Id of the created breakpoint for further reference. +// - `retActualLocation`: Location this breakpoint resolved into. +func (doDebugger Debugger) SetBreakpoint(location *debugger.Location, condition *string) (retBreakpointID debugger.BreakpointID, retActualLocation *debugger.Location, err error) { + b := debugger.SetBreakpoint(location) + if condition != nil { + b = b.WithCondition(*condition) + } + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetInstrumentationBreakpoint sets instrumentation breakpoint. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setInstrumentationBreakpoint +// +// parameters: +// - `instrumentation`: Instrumentation name. +// +// returns: +// - `retBreakpointID`: Id of the created breakpoint for further reference. +func (doDebugger Debugger) SetInstrumentationBreakpoint(instrumentation debugger.SetInstrumentationBreakpointInstrumentation) (retBreakpointID debugger.BreakpointID, err error) { + b := debugger.SetInstrumentationBreakpoint(instrumentation) + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetBreakpointByURL sets JavaScript breakpoint at given location specified +// either by URL or URL regex. Once this command is issued, all existing parsed +// scripts will have breakpoints resolved and returned in locations property. +// Further matching script parsing will result in subsequent breakpointResolved +// events issued. This logical breakpoint will survive page reloads. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBreakpointByUrl +// +// parameters: +// - `lineNumber`: Line number to set breakpoint at. +// - `url`: This can be nil. (Optional) URL of the resources to set breakpoint on. +// - `urlRegex`: This can be nil. (Optional) Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. +// - `scriptHash`: This can be nil. (Optional) Script hash of the resources to set breakpoint on. +// - `columnNumber`: This can be nil. (Optional) Offset in the line to set breakpoint at. +// - `condition`: This can be nil. (Optional) Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. +// +// returns: +// - `retBreakpointID`: Id of the created breakpoint for further reference. +// - `retLocations`: List of the locations this breakpoint resolved into upon addition. +func (doDebugger Debugger) SetBreakpointByURL(lineNumber int64, url *string, urlRegex *string, scriptHash *string, columnNumber *int64, condition *string) (retBreakpointID debugger.BreakpointID, retLocations []*debugger.Location, err error) { + b := debugger.SetBreakpointByURL(lineNumber) + if url != nil { + b = b.WithURL(*url) + } + if urlRegex != nil { + b = b.WithURLRegex(*urlRegex) + } + if scriptHash != nil { + b = b.WithScriptHash(*scriptHash) + } + if columnNumber != nil { + b = b.WithColumnNumber(*columnNumber) + } + if condition != nil { + b = b.WithCondition(*condition) + } + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetBreakpointOnFunctionCall sets JavaScript breakpoint before each call to +// the given function. If another function was created from the same source as a +// given one, calling it will also trigger the breakpoint. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBreakpointOnFunctionCall +// +// parameters: +// - `objectID`: Function object id. +// - `condition`: This can be nil. (Optional) Expression to use as a breakpoint condition. When specified, debugger will stop on the breakpoint if this expression evaluates to true. +// +// returns: +// - `retBreakpointID`: Id of the created breakpoint for further reference. +func (doDebugger Debugger) SetBreakpointOnFunctionCall(objectID runtime.RemoteObjectID, condition *string) (retBreakpointID debugger.BreakpointID, err error) { + b := debugger.SetBreakpointOnFunctionCall(objectID) + if condition != nil { + b = b.WithCondition(*condition) + } + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetBreakpointsActive activates / deactivates all breakpoints on the page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setBreakpointsActive +// +// parameters: +// - `active`: New value for breakpoints active state. +func (doDebugger Debugger) SetBreakpointsActive(active bool) (err error) { + b := debugger.SetBreakpointsActive(active) + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetPauseOnExceptions defines pause on exceptions state. Can be set to stop +// on all exceptions, uncaught exceptions or no exceptions. Initial pause on +// exceptions state is none. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setPauseOnExceptions +// +// parameters: +// - `state`: Pause on exceptions mode. +func (doDebugger Debugger) SetPauseOnExceptions(state debugger.ExceptionsState) (err error) { + b := debugger.SetPauseOnExceptions(state) + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetReturnValue changes return value in top frame. Available only at return +// break position. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setReturnValue +// +// parameters: +// - `newValue`: New return value. +func (doDebugger Debugger) SetReturnValue(newValue *runtime.CallArgument) (err error) { + b := debugger.SetReturnValue(newValue) + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetScriptSource edits JavaScript source live. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setScriptSource +// +// parameters: +// - `scriptID`: Id of the script to edit. +// - `scriptSource`: New content of the script. +// - `dryRun`: This can be nil. (Optional) If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. +// +// returns: +// - `retCallFrames`: New stack trace in case editing has happened while VM was stopped. +// - `retStackChanged`: Whether current call stack was modified after applying the changes. +// - `retAsyncStackTrace`: Async stack trace, if any. +// - `retAsyncStackTraceID`: Async stack trace, if any. +// - `retExceptionDetails`: Exception details if any. +func (doDebugger Debugger) SetScriptSource(scriptID runtime.ScriptID, scriptSource string, dryRun *bool) (retCallFrames []*debugger.CallFrame, retStackChanged bool, retAsyncStackTrace *runtime.StackTrace, retAsyncStackTraceID *runtime.StackTraceID, retExceptionDetails *runtime.ExceptionDetails, err error) { + b := debugger.SetScriptSource(scriptID, scriptSource) + if dryRun != nil { + b = b.WithDryRun(*dryRun) + } + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetSkipAllPauses makes page not interrupt on any pauses (breakpoint, +// exception, dom exception etc). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setSkipAllPauses +// +// parameters: +// - `skip`: New value for skip pauses state. +func (doDebugger Debugger) SetSkipAllPauses(skip bool) (err error) { + b := debugger.SetSkipAllPauses(skip) + return b.Do(doDebugger.ctxWithExecutor) +} + +// SetVariableValue changes value of variable in a callframe. Object-based +// scopes are not supported and must be mutated manually. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-setVariableValue +// +// parameters: +// - `scopeNumber`: 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. +// - `variableName`: Variable name. +// - `newValue`: New variable value. +// - `callFrameID`: Id of callframe that holds variable. +func (doDebugger Debugger) SetVariableValue(scopeNumber int64, variableName string, newValue *runtime.CallArgument, callFrameID debugger.CallFrameID) (err error) { + b := debugger.SetVariableValue(scopeNumber, variableName, newValue, callFrameID) + return b.Do(doDebugger.ctxWithExecutor) +} + +// StepInto steps into the function call. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-stepInto +// +// parameters: +// - `breakOnAsyncCall`: This can be nil. (Optional) Debugger will pause on the execution of the first async task which was scheduled before next pause. +func (doDebugger Debugger) StepInto(breakOnAsyncCall *bool) (err error) { + b := debugger.StepInto() + if breakOnAsyncCall != nil { + b = b.WithBreakOnAsyncCall(*breakOnAsyncCall) + } + return b.Do(doDebugger.ctxWithExecutor) +} + +// StepOut steps out of the function call. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-stepOut +func (doDebugger Debugger) StepOut() (err error) { + b := debugger.StepOut() + return b.Do(doDebugger.ctxWithExecutor) +} + +// StepOver steps over the statement. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Debugger#method-stepOver +func (doDebugger Debugger) StepOver() (err error) { + b := debugger.StepOver() + return b.Do(doDebugger.ctxWithExecutor) +} diff --git a/domain/deviceorientation.go b/domain/deviceorientation.go new file mode 100644 index 0000000..8b7fdd6 --- /dev/null +++ b/domain/deviceorientation.go @@ -0,0 +1,35 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/deviceorientation" +) + +// DeviceOrientation executes a cdproto command under DeviceOrientation domain. +type DeviceOrientation struct { + ctxWithExecutor context.Context +} + +// ClearDeviceOrientationOverride clears the overridden Device Orientation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DeviceOrientation#method-clearDeviceOrientationOverride +func (doDeviceOrientation DeviceOrientation) ClearDeviceOrientationOverride() (err error) { + b := deviceorientation.ClearDeviceOrientationOverride() + return b.Do(doDeviceOrientation.ctxWithExecutor) +} + +// SetDeviceOrientationOverride overrides the Device Orientation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DeviceOrientation#method-setDeviceOrientationOverride +// +// parameters: +// - `alpha`: Mock alpha +// - `beta`: Mock beta +// - `gamma`: Mock gamma +func (doDeviceOrientation DeviceOrientation) SetDeviceOrientationOverride(alpha float64, beta float64, gamma float64) (err error) { + b := deviceorientation.SetDeviceOrientationOverride(alpha, beta, gamma) + return b.Do(doDeviceOrientation.ctxWithExecutor) +} diff --git a/domain/dom.go b/domain/dom.go new file mode 100644 index 0000000..ed9189a --- /dev/null +++ b/domain/dom.go @@ -0,0 +1,706 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/dom" + "github.com/chromedp/cdproto/runtime" +) + +// DOM executes a cdproto command under DOM domain. +type DOM struct { + ctxWithExecutor context.Context +} + +// CollectClassNamesFromSubtree collects class names for the node with given +// id and all of it's child nodes. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-collectClassNamesFromSubtree +// +// parameters: +// - `nodeID`: Id of the node to collect class names. +// +// returns: +// - `retClassNames`: Class name list. +func (doDOM DOM) CollectClassNamesFromSubtree(nodeID cdp.NodeID) (retClassNames []string, err error) { + b := dom.CollectClassNamesFromSubtree(nodeID) + return b.Do(doDOM.ctxWithExecutor) +} + +// CopyTo creates a deep copy of the specified node and places it into the +// target container before the given anchor. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-copyTo +// +// parameters: +// - `nodeID`: Id of the node to copy. +// - `targetNodeID`: Id of the element to drop the copy into. +// - `insertBeforeNodeID`: This can be nil. (Optional) Drop the copy before this node (if absent, the copy becomes the last child of targetNodeId). +// +// returns: +// - `retNodeID`: Id of the node clone. +func (doDOM DOM) CopyTo(nodeID cdp.NodeID, targetNodeID cdp.NodeID, insertBeforeNodeID *cdp.NodeID) (retNodeID cdp.NodeID, err error) { + b := dom.CopyTo(nodeID, targetNodeID) + if insertBeforeNodeID != nil { + b = b.WithInsertBeforeNodeID(*insertBeforeNodeID) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// DescribeNode describes node given its id, does not require domain to be +// enabled. Does not start tracking any objects, can be used for automation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-describeNode +// +// parameters: +// - `nodeID`: This can be nil. (Optional) Identifier of the node. +// - `backendNodeID`: This can be nil. (Optional) Identifier of the backend node. +// - `objectID`: This can be nil. (Optional) JavaScript object id of the node wrapper. +// - `depth`: This can be nil. (Optional) The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. +// - `pierce`: This can be nil. (Optional) Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). +// +// returns: +// - `retNode`: Node description. +func (doDOM DOM) DescribeNode(nodeID *cdp.NodeID, backendNodeID *cdp.BackendNodeID, objectID *runtime.RemoteObjectID, depth *int64, pierce *bool) (retNode *cdp.Node, err error) { + b := dom.DescribeNode() + if nodeID != nil { + b = b.WithNodeID(*nodeID) + } + if backendNodeID != nil { + b = b.WithBackendNodeID(*backendNodeID) + } + if objectID != nil { + b = b.WithObjectID(*objectID) + } + if depth != nil { + b = b.WithDepth(*depth) + } + if pierce != nil { + b = b.WithPierce(*pierce) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// Disable disables DOM agent for the given page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-disable +func (doDOM DOM) Disable() (err error) { + b := dom.Disable() + return b.Do(doDOM.ctxWithExecutor) +} + +// DiscardSearchResults discards search results from the session with the +// given id. getSearchResults should no longer be called for that search. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-discardSearchResults +// +// parameters: +// - `searchID`: Unique search session identifier. +func (doDOM DOM) DiscardSearchResults(searchID string) (err error) { + b := dom.DiscardSearchResults(searchID) + return b.Do(doDOM.ctxWithExecutor) +} + +// Enable enables DOM agent for the given page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-enable +func (doDOM DOM) Enable() (err error) { + b := dom.Enable() + return b.Do(doDOM.ctxWithExecutor) +} + +// Focus focuses the given element. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-focus +// +// parameters: +// - `nodeID`: This can be nil. (Optional) Identifier of the node. +// - `backendNodeID`: This can be nil. (Optional) Identifier of the backend node. +// - `objectID`: This can be nil. (Optional) JavaScript object id of the node wrapper. +func (doDOM DOM) Focus(nodeID *cdp.NodeID, backendNodeID *cdp.BackendNodeID, objectID *runtime.RemoteObjectID) (err error) { + b := dom.Focus() + if nodeID != nil { + b = b.WithNodeID(*nodeID) + } + if backendNodeID != nil { + b = b.WithBackendNodeID(*backendNodeID) + } + if objectID != nil { + b = b.WithObjectID(*objectID) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// GetAttributes returns attributes for the specified node. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getAttributes +// +// parameters: +// - `nodeID`: Id of the node to retrieve attibutes for. +// +// returns: +// - `retAttributes`: An interleaved array of node attribute names and values. +func (doDOM DOM) GetAttributes(nodeID cdp.NodeID) (retAttributes []string, err error) { + b := dom.GetAttributes(nodeID) + return b.Do(doDOM.ctxWithExecutor) +} + +// GetBoxModel returns boxes for the given node. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getBoxModel +// +// parameters: +// - `nodeID`: This can be nil. (Optional) Identifier of the node. +// - `backendNodeID`: This can be nil. (Optional) Identifier of the backend node. +// - `objectID`: This can be nil. (Optional) JavaScript object id of the node wrapper. +// +// returns: +// - `retModel`: Box model for the node. +func (doDOM DOM) GetBoxModel(nodeID *cdp.NodeID, backendNodeID *cdp.BackendNodeID, objectID *runtime.RemoteObjectID) (retModel *dom.BoxModel, err error) { + b := dom.GetBoxModel() + if nodeID != nil { + b = b.WithNodeID(*nodeID) + } + if backendNodeID != nil { + b = b.WithBackendNodeID(*backendNodeID) + } + if objectID != nil { + b = b.WithObjectID(*objectID) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// GetContentQuads returns quads that describe node position on the page. +// This method might return multiple quads for inline nodes. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getContentQuads +// +// parameters: +// - `nodeID`: This can be nil. (Optional) Identifier of the node. +// - `backendNodeID`: This can be nil. (Optional) Identifier of the backend node. +// - `objectID`: This can be nil. (Optional) JavaScript object id of the node wrapper. +// +// returns: +// - `retQuads`: Quads that describe node layout relative to viewport. +func (doDOM DOM) GetContentQuads(nodeID *cdp.NodeID, backendNodeID *cdp.BackendNodeID, objectID *runtime.RemoteObjectID) (retQuads []dom.Quad, err error) { + b := dom.GetContentQuads() + if nodeID != nil { + b = b.WithNodeID(*nodeID) + } + if backendNodeID != nil { + b = b.WithBackendNodeID(*backendNodeID) + } + if objectID != nil { + b = b.WithObjectID(*objectID) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// GetDocument returns the root DOM node (and optionally the subtree) to the +// caller. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getDocument +// +// parameters: +// - `depth`: This can be nil. (Optional) The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. +// - `pierce`: This can be nil. (Optional) Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). +// +// returns: +// - `retRoot`: Resulting node. +func (doDOM DOM) GetDocument(depth *int64, pierce *bool) (retRoot *cdp.Node, err error) { + b := dom.GetDocument() + if depth != nil { + b = b.WithDepth(*depth) + } + if pierce != nil { + b = b.WithPierce(*pierce) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// GetFlattenedDocument returns the root DOM node (and optionally the +// subtree) to the caller. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getFlattenedDocument +// +// parameters: +// - `depth`: This can be nil. (Optional) The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. +// - `pierce`: This can be nil. (Optional) Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). +// +// returns: +// - `retNodes`: Resulting node. +func (doDOM DOM) GetFlattenedDocument(depth *int64, pierce *bool) (retNodes []*cdp.Node, err error) { + b := dom.GetFlattenedDocument() + if depth != nil { + b = b.WithDepth(*depth) + } + if pierce != nil { + b = b.WithPierce(*pierce) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// GetNodeForLocation returns node id at given location. Depending on whether +// DOM domain is enabled, nodeId is either returned or not. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getNodeForLocation +// +// parameters: +// - `x`: X coordinate. +// - `y`: Y coordinate. +// - `includeUserAgentShadowDOM`: This can be nil. (Optional) False to skip to the nearest non-UA shadow root ancestor (default: false). +// - `ignorePointerEventsNone`: This can be nil. (Optional) Whether to ignore pointer-events: none on elements and hit test them. +// +// returns: +// - `retBackendNodeID`: Resulting node. +// - `retFrameID`: Frame this node belongs to. +// - `retNodeID`: Id of the node at given coordinates, only when enabled and requested document. +func (doDOM DOM) GetNodeForLocation(x int64, y int64, includeUserAgentShadowDOM *bool, ignorePointerEventsNone *bool) (retBackendNodeID cdp.BackendNodeID, retFrameID cdp.FrameID, retNodeID cdp.NodeID, err error) { + b := dom.GetNodeForLocation(x, y) + if includeUserAgentShadowDOM != nil { + b = b.WithIncludeUserAgentShadowDOM(*includeUserAgentShadowDOM) + } + if ignorePointerEventsNone != nil { + b = b.WithIgnorePointerEventsNone(*ignorePointerEventsNone) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// GetOuterHTML returns node's HTML markup. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getOuterHTML +// +// parameters: +// - `nodeID`: This can be nil. (Optional) Identifier of the node. +// - `backendNodeID`: This can be nil. (Optional) Identifier of the backend node. +// - `objectID`: This can be nil. (Optional) JavaScript object id of the node wrapper. +// +// returns: +// - `retOuterHTML`: Outer HTML markup. +func (doDOM DOM) GetOuterHTML(nodeID *cdp.NodeID, backendNodeID *cdp.BackendNodeID, objectID *runtime.RemoteObjectID) (retOuterHTML string, err error) { + b := dom.GetOuterHTML() + if nodeID != nil { + b = b.WithNodeID(*nodeID) + } + if backendNodeID != nil { + b = b.WithBackendNodeID(*backendNodeID) + } + if objectID != nil { + b = b.WithObjectID(*objectID) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// GetRelayoutBoundary returns the id of the nearest ancestor that is a +// relayout boundary. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getRelayoutBoundary +// +// parameters: +// - `nodeID`: Id of the node. +// +// returns: +// - `retNodeID`: Relayout boundary node id for the given node. +func (doDOM DOM) GetRelayoutBoundary(nodeID cdp.NodeID) (retNodeID cdp.NodeID, err error) { + b := dom.GetRelayoutBoundary(nodeID) + return b.Do(doDOM.ctxWithExecutor) +} + +// GetSearchResults returns search results from given fromIndex to given +// toIndex from the search with the given identifier. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getSearchResults +// +// parameters: +// - `searchID`: Unique search session identifier. +// - `fromIndex`: Start index of the search result to be returned. +// - `toIndex`: End index of the search result to be returned. +// +// returns: +// - `retNodeIds`: Ids of the search result nodes. +func (doDOM DOM) GetSearchResults(searchID string, fromIndex int64, toIndex int64) (retNodeIds []cdp.NodeID, err error) { + b := dom.GetSearchResults(searchID, fromIndex, toIndex) + return b.Do(doDOM.ctxWithExecutor) +} + +// MarkUndoableState marks last undoable state. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-markUndoableState +func (doDOM DOM) MarkUndoableState() (err error) { + b := dom.MarkUndoableState() + return b.Do(doDOM.ctxWithExecutor) +} + +// MoveTo moves node into the new container, places it before the given +// anchor. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-moveTo +// +// parameters: +// - `nodeID`: Id of the node to move. +// - `targetNodeID`: Id of the element to drop the moved node into. +// - `insertBeforeNodeID`: This can be nil. (Optional) Drop node before this one (if absent, the moved node becomes the last child of targetNodeId). +// +// returns: +// - `retNodeID`: New id of the moved node. +func (doDOM DOM) MoveTo(nodeID cdp.NodeID, targetNodeID cdp.NodeID, insertBeforeNodeID *cdp.NodeID) (retNodeID cdp.NodeID, err error) { + b := dom.MoveTo(nodeID, targetNodeID) + if insertBeforeNodeID != nil { + b = b.WithInsertBeforeNodeID(*insertBeforeNodeID) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// PerformSearch searches for a given string in the DOM tree. Use +// getSearchResults to access search results or cancelSearch to end this search +// session. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-performSearch +// +// parameters: +// - `query`: Plain text or query selector or XPath search query. +// - `includeUserAgentShadowDOM`: This can be nil. (Optional) True to search in user agent shadow DOM. +// +// returns: +// - `retSearchID`: Unique search session identifier. +// - `retResultCount`: Number of search results. +func (doDOM DOM) PerformSearch(query string, includeUserAgentShadowDOM *bool) (retSearchID string, retResultCount int64, err error) { + b := dom.PerformSearch(query) + if includeUserAgentShadowDOM != nil { + b = b.WithIncludeUserAgentShadowDOM(*includeUserAgentShadowDOM) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// PushNodeByPathToFrontend requests that the node is sent to the caller +// given its path. // FIXME, use XPath. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-pushNodeByPathToFrontend +// +// parameters: +// - `path`: Path to node in the proprietary format. +// +// returns: +// - `retNodeID`: Id of the node for given path. +func (doDOM DOM) PushNodeByPathToFrontend(path string) (retNodeID cdp.NodeID, err error) { + b := dom.PushNodeByPathToFrontend(path) + return b.Do(doDOM.ctxWithExecutor) +} + +// PushNodesByBackendIdsToFrontend requests that a batch of nodes is sent to +// the caller given their backend node ids. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-pushNodesByBackendIdsToFrontend +// +// parameters: +// - `backendNodeIds`: The array of backend node ids. +// +// returns: +// - `retNodeIds`: The array of ids of pushed nodes that correspond to the backend ids specified in backendNodeIds. +func (doDOM DOM) PushNodesByBackendIdsToFrontend(backendNodeIds []cdp.BackendNodeID) (retNodeIds []cdp.NodeID, err error) { + b := dom.PushNodesByBackendIdsToFrontend(backendNodeIds) + return b.Do(doDOM.ctxWithExecutor) +} + +// QuerySelector executes querySelector on a given node. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-querySelector +// +// parameters: +// - `nodeID`: Id of the node to query upon. +// - `selector`: Selector string. +// +// returns: +// - `retNodeID`: Query selector result. +func (doDOM DOM) QuerySelector(nodeID cdp.NodeID, selector string) (retNodeID cdp.NodeID, err error) { + b := dom.QuerySelector(nodeID, selector) + return b.Do(doDOM.ctxWithExecutor) +} + +// QuerySelectorAll executes querySelectorAll on a given node. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-querySelectorAll +// +// parameters: +// - `nodeID`: Id of the node to query upon. +// - `selector`: Selector string. +// +// returns: +// - `retNodeIds`: Query selector result. +func (doDOM DOM) QuerySelectorAll(nodeID cdp.NodeID, selector string) (retNodeIds []cdp.NodeID, err error) { + b := dom.QuerySelectorAll(nodeID, selector) + return b.Do(doDOM.ctxWithExecutor) +} + +// Redo re-does the last undone action. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-redo +func (doDOM DOM) Redo() (err error) { + b := dom.Redo() + return b.Do(doDOM.ctxWithExecutor) +} + +// RemoveAttribute removes attribute with given name from an element with +// given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-removeAttribute +// +// parameters: +// - `nodeID`: Id of the element to remove attribute from. +// - `name`: Name of the attribute to remove. +func (doDOM DOM) RemoveAttribute(nodeID cdp.NodeID, name string) (err error) { + b := dom.RemoveAttribute(nodeID, name) + return b.Do(doDOM.ctxWithExecutor) +} + +// RemoveNode removes node with given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-removeNode +// +// parameters: +// - `nodeID`: Id of the node to remove. +func (doDOM DOM) RemoveNode(nodeID cdp.NodeID) (err error) { + b := dom.RemoveNode(nodeID) + return b.Do(doDOM.ctxWithExecutor) +} + +// RequestChildNodes requests that children of the node with given id are +// returned to the caller in form of setChildNodes events where not only +// immediate children are retrieved, but all children down to the specified +// depth. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-requestChildNodes +// +// parameters: +// - `nodeID`: Id of the node to get children for. +// - `depth`: This can be nil. (Optional) The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. +// - `pierce`: This can be nil. (Optional) Whether or not iframes and shadow roots should be traversed when returning the sub-tree (default is false). +func (doDOM DOM) RequestChildNodes(nodeID cdp.NodeID, depth *int64, pierce *bool) (err error) { + b := dom.RequestChildNodes(nodeID) + if depth != nil { + b = b.WithDepth(*depth) + } + if pierce != nil { + b = b.WithPierce(*pierce) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// RequestNode requests that the node is sent to the caller given the +// JavaScript node object reference. All nodes that form the path from the node +// to the root are also sent to the client as a series of setChildNodes +// notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-requestNode +// +// parameters: +// - `objectID`: JavaScript object id to convert into node. +// +// returns: +// - `retNodeID`: Node id for given object. +func (doDOM DOM) RequestNode(objectID runtime.RemoteObjectID) (retNodeID cdp.NodeID, err error) { + b := dom.RequestNode(objectID) + return b.Do(doDOM.ctxWithExecutor) +} + +// ResolveNode resolves the JavaScript node object for a given NodeId or +// BackendNodeId. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-resolveNode +// +// parameters: +// - `nodeID`: This can be nil. (Optional) Id of the node to resolve. +// - `backendNodeID`: This can be nil. (Optional) Backend identifier of the node to resolve. +// - `objectGroup`: This can be nil. (Optional) Symbolic group name that can be used to release multiple objects. +// - `executionContextID`: This can be nil. (Optional) Execution context in which to resolve the node. +// +// returns: +// - `retObject`: JavaScript object wrapper for given node. +func (doDOM DOM) ResolveNode(nodeID *cdp.NodeID, backendNodeID *cdp.BackendNodeID, objectGroup *string, executionContextID *runtime.ExecutionContextID) (retObject *runtime.RemoteObject, err error) { + b := dom.ResolveNode() + if nodeID != nil { + b = b.WithNodeID(*nodeID) + } + if backendNodeID != nil { + b = b.WithBackendNodeID(*backendNodeID) + } + if objectGroup != nil { + b = b.WithObjectGroup(*objectGroup) + } + if executionContextID != nil { + b = b.WithExecutionContextID(*executionContextID) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// SetAttributeValue sets attribute for an element with given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setAttributeValue +// +// parameters: +// - `nodeID`: Id of the element to set attribute for. +// - `name`: Attribute name. +// - `value`: Attribute value. +func (doDOM DOM) SetAttributeValue(nodeID cdp.NodeID, name string, value string) (err error) { + b := dom.SetAttributeValue(nodeID, name, value) + return b.Do(doDOM.ctxWithExecutor) +} + +// SetAttributesAsText sets attributes on element with given id. This method +// is useful when user edits some existing attribute value and types in several +// attribute name/value pairs. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setAttributesAsText +// +// parameters: +// - `nodeID`: Id of the element to set attributes for. +// - `text`: Text with a number of attributes. Will parse this text using HTML parser. +// - `name`: This can be nil. (Optional) Attribute name to replace with new attributes derived from text in case text parsed successfully. +func (doDOM DOM) SetAttributesAsText(nodeID cdp.NodeID, text string, name *string) (err error) { + b := dom.SetAttributesAsText(nodeID, text) + if name != nil { + b = b.WithName(*name) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// SetFileInputFiles sets files for the given file input element. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setFileInputFiles +// +// parameters: +// - `files`: Array of file paths to set. +// - `nodeID`: This can be nil. (Optional) Identifier of the node. +// - `backendNodeID`: This can be nil. (Optional) Identifier of the backend node. +// - `objectID`: This can be nil. (Optional) JavaScript object id of the node wrapper. +func (doDOM DOM) SetFileInputFiles(files []string, nodeID *cdp.NodeID, backendNodeID *cdp.BackendNodeID, objectID *runtime.RemoteObjectID) (err error) { + b := dom.SetFileInputFiles(files) + if nodeID != nil { + b = b.WithNodeID(*nodeID) + } + if backendNodeID != nil { + b = b.WithBackendNodeID(*backendNodeID) + } + if objectID != nil { + b = b.WithObjectID(*objectID) + } + return b.Do(doDOM.ctxWithExecutor) +} + +// SetNodeStackTracesEnabled sets if stack traces should be captured for +// Nodes. See Node.getNodeStackTraces. Default is disabled. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setNodeStackTracesEnabled +// +// parameters: +// - `enable`: Enable or disable. +func (doDOM DOM) SetNodeStackTracesEnabled(enable bool) (err error) { + b := dom.SetNodeStackTracesEnabled(enable) + return b.Do(doDOM.ctxWithExecutor) +} + +// GetNodeStackTraces gets stack traces associated with a Node. As of now, +// only provides stack trace for Node creation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getNodeStackTraces +// +// parameters: +// - `nodeID`: Id of the node to get stack traces for. +// +// returns: +// - `retCreation`: Creation stack trace, if available. +func (doDOM DOM) GetNodeStackTraces(nodeID cdp.NodeID) (retCreation *runtime.StackTrace, err error) { + b := dom.GetNodeStackTraces(nodeID) + return b.Do(doDOM.ctxWithExecutor) +} + +// GetFileInfo returns file information for the given File wrapper. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getFileInfo +// +// parameters: +// - `objectID`: JavaScript object id of the node wrapper. +// +// returns: +// - `retPath` +func (doDOM DOM) GetFileInfo(objectID runtime.RemoteObjectID) (retPath string, err error) { + b := dom.GetFileInfo(objectID) + return b.Do(doDOM.ctxWithExecutor) +} + +// SetInspectedNode enables console to refer to the node with given id via $x +// (see Command Line API for more details $x functions). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setInspectedNode +// +// parameters: +// - `nodeID`: DOM node id to be accessible by means of $x command line API. +func (doDOM DOM) SetInspectedNode(nodeID cdp.NodeID) (err error) { + b := dom.SetInspectedNode(nodeID) + return b.Do(doDOM.ctxWithExecutor) +} + +// SetNodeName sets node name for a node with given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setNodeName +// +// parameters: +// - `nodeID`: Id of the node to set name for. +// - `name`: New node's name. +// +// returns: +// - `retNodeID`: New node's id. +func (doDOM DOM) SetNodeName(nodeID cdp.NodeID, name string) (retNodeID cdp.NodeID, err error) { + b := dom.SetNodeName(nodeID, name) + return b.Do(doDOM.ctxWithExecutor) +} + +// SetNodeValue sets node value for a node with given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setNodeValue +// +// parameters: +// - `nodeID`: Id of the node to set value for. +// - `value`: New node's value. +func (doDOM DOM) SetNodeValue(nodeID cdp.NodeID, value string) (err error) { + b := dom.SetNodeValue(nodeID, value) + return b.Do(doDOM.ctxWithExecutor) +} + +// SetOuterHTML sets node HTML markup, returns new node id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setOuterHTML +// +// parameters: +// - `nodeID`: Id of the node to set markup for. +// - `outerHTML`: Outer HTML markup to set. +func (doDOM DOM) SetOuterHTML(nodeID cdp.NodeID, outerHTML string) (err error) { + b := dom.SetOuterHTML(nodeID, outerHTML) + return b.Do(doDOM.ctxWithExecutor) +} + +// Undo undoes the last performed action. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-undo +func (doDOM DOM) Undo() (err error) { + b := dom.Undo() + return b.Do(doDOM.ctxWithExecutor) +} + +// GetFrameOwner returns iframe node that owns iframe with the given domain. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-getFrameOwner +// +// parameters: +// - `frameID` +// +// returns: +// - `retBackendNodeID`: Resulting node. +// - `retNodeID`: Id of the node at given coordinates, only when enabled and requested document. +func (doDOM DOM) GetFrameOwner(frameID cdp.FrameID) (retBackendNodeID cdp.BackendNodeID, retNodeID cdp.NodeID, err error) { + b := dom.GetFrameOwner(frameID) + return b.Do(doDOM.ctxWithExecutor) +} diff --git a/domain/domain.go b/domain/domain.go new file mode 100644 index 0000000..816cd20 --- /dev/null +++ b/domain/domain.go @@ -0,0 +1,241 @@ + +/* +Package domain helps executing cdproto commands. +*/ +package domain + +import ( + "context" +) + +// Domain executes a cdproto command against a chromedp context. +type Domain struct { + ctxWithExecutor context.Context // chromedp context +} + +// Do makes a Domain that executes a cdproto command against a chromedp context. +// Set up arg `ctxWithExecutor` with `cdp.WithExecutor()` and `chromedp.FromContext()` beforehand. +func Do(ctxWithExecutor context.Context) Domain { + return Domain{ctxWithExecutor} +} + +// Accessibility executes a cdproto command under Accessibility domain. +func (d Domain) Accessibility() Accessibility { + return Accessibility{d.ctxWithExecutor} +} + +// Animation executes a cdproto command under Animation domain. +func (d Domain) Animation() Animation { + return Animation{d.ctxWithExecutor} +} + +// ApplicationCache executes a cdproto command under ApplicationCache domain. +func (d Domain) ApplicationCache() ApplicationCache { + return ApplicationCache{d.ctxWithExecutor} +} + +// Audits executes a cdproto command under Audits domain. +func (d Domain) Audits() Audits { + return Audits{d.ctxWithExecutor} +} + +// BackgroundService executes a cdproto command under BackgroundService domain. +func (d Domain) BackgroundService() BackgroundService { + return BackgroundService{d.ctxWithExecutor} +} + +// Browser executes a cdproto command under Browser domain. +func (d Domain) Browser() Browser { + return Browser{d.ctxWithExecutor} +} + +// CSS executes a cdproto command under CSS domain. +func (d Domain) CSS() CSS { + return CSS{d.ctxWithExecutor} +} + +// CacheStorage executes a cdproto command under CacheStorage domain. +func (d Domain) CacheStorage() CacheStorage { + return CacheStorage{d.ctxWithExecutor} +} + +// Cast executes a cdproto command under Cast domain. +func (d Domain) Cast() Cast { + return Cast{d.ctxWithExecutor} +} + +// DOM executes a cdproto command under DOM domain. +func (d Domain) DOM() DOM { + return DOM{d.ctxWithExecutor} +} + +// DOMDebugger executes a cdproto command under DOMDebugger domain. +func (d Domain) DOMDebugger() DOMDebugger { + return DOMDebugger{d.ctxWithExecutor} +} + +// DOMSnapshot executes a cdproto command under DOMSnapshot domain. +func (d Domain) DOMSnapshot() DOMSnapshot { + return DOMSnapshot{d.ctxWithExecutor} +} + +// DOMStorage executes a cdproto command under DOMStorage domain. +func (d Domain) DOMStorage() DOMStorage { + return DOMStorage{d.ctxWithExecutor} +} + +// Database executes a cdproto command under Database domain. +func (d Domain) Database() Database { + return Database{d.ctxWithExecutor} +} + +// Debugger executes a cdproto command under Debugger domain. +func (d Domain) Debugger() Debugger { + return Debugger{d.ctxWithExecutor} +} + +// DeviceOrientation executes a cdproto command under DeviceOrientation domain. +func (d Domain) DeviceOrientation() DeviceOrientation { + return DeviceOrientation{d.ctxWithExecutor} +} + +// Emulation executes a cdproto command under Emulation domain. +func (d Domain) Emulation() Emulation { + return Emulation{d.ctxWithExecutor} +} + +// Fetch executes a cdproto command under Fetch domain. +func (d Domain) Fetch() Fetch { + return Fetch{d.ctxWithExecutor} +} + +// HAR executes a cdproto command under HAR domain. +func (d Domain) HAR() HAR { + return HAR{d.ctxWithExecutor} +} + +// HeadlessExperimental executes a cdproto command under HeadlessExperimental domain. +func (d Domain) HeadlessExperimental() HeadlessExperimental { + return HeadlessExperimental{d.ctxWithExecutor} +} + +// HeapProfiler executes a cdproto command under HeapProfiler domain. +func (d Domain) HeapProfiler() HeapProfiler { + return HeapProfiler{d.ctxWithExecutor} +} + +// IO executes a cdproto command under IO domain. +func (d Domain) IO() IO { + return IO{d.ctxWithExecutor} +} + +// IndexedDB executes a cdproto command under IndexedDB domain. +func (d Domain) IndexedDB() IndexedDB { + return IndexedDB{d.ctxWithExecutor} +} + +// Input executes a cdproto command under Input domain. +func (d Domain) Input() Input { + return Input{d.ctxWithExecutor} +} + +// Inspector executes a cdproto command under Inspector domain. +func (d Domain) Inspector() Inspector { + return Inspector{d.ctxWithExecutor} +} + +// LayerTree executes a cdproto command under LayerTree domain. +func (d Domain) LayerTree() LayerTree { + return LayerTree{d.ctxWithExecutor} +} + +// Log executes a cdproto command under Log domain. +func (d Domain) Log() Log { + return Log{d.ctxWithExecutor} +} + +// Media executes a cdproto command under Media domain. +func (d Domain) Media() Media { + return Media{d.ctxWithExecutor} +} + +// Memory executes a cdproto command under Memory domain. +func (d Domain) Memory() Memory { + return Memory{d.ctxWithExecutor} +} + +// Network executes a cdproto command under Network domain. +func (d Domain) Network() Network { + return Network{d.ctxWithExecutor} +} + +// Overlay executes a cdproto command under Overlay domain. +func (d Domain) Overlay() Overlay { + return Overlay{d.ctxWithExecutor} +} + +// Page executes a cdproto command under Page domain. +func (d Domain) Page() Page { + return Page{d.ctxWithExecutor} +} + +// Performance executes a cdproto command under Performance domain. +func (d Domain) Performance() Performance { + return Performance{d.ctxWithExecutor} +} + +// Profiler executes a cdproto command under Profiler domain. +func (d Domain) Profiler() Profiler { + return Profiler{d.ctxWithExecutor} +} + +// Runtime executes a cdproto command under Runtime domain. +func (d Domain) Runtime() Runtime { + return Runtime{d.ctxWithExecutor} +} + +// Security executes a cdproto command under Security domain. +func (d Domain) Security() Security { + return Security{d.ctxWithExecutor} +} + +// ServiceWorker executes a cdproto command under ServiceWorker domain. +func (d Domain) ServiceWorker() ServiceWorker { + return ServiceWorker{d.ctxWithExecutor} +} + +// Storage executes a cdproto command under Storage domain. +func (d Domain) Storage() Storage { + return Storage{d.ctxWithExecutor} +} + +// SystemInfo executes a cdproto command under SystemInfo domain. +func (d Domain) SystemInfo() SystemInfo { + return SystemInfo{d.ctxWithExecutor} +} + +// Target executes a cdproto command under Target domain. +func (d Domain) Target() Target { + return Target{d.ctxWithExecutor} +} + +// Tethering executes a cdproto command under Tethering domain. +func (d Domain) Tethering() Tethering { + return Tethering{d.ctxWithExecutor} +} + +// Tracing executes a cdproto command under Tracing domain. +func (d Domain) Tracing() Tracing { + return Tracing{d.ctxWithExecutor} +} + +// WebAudio executes a cdproto command under WebAudio domain. +func (d Domain) WebAudio() WebAudio { + return WebAudio{d.ctxWithExecutor} +} + +// WebAuthn executes a cdproto command under WebAuthn domain. +func (d Domain) WebAuthn() WebAuthn { + return WebAuthn{d.ctxWithExecutor} +} + diff --git a/domain/domdebugger.go b/domain/domdebugger.go new file mode 100644 index 0000000..b1c9c24 --- /dev/null +++ b/domain/domdebugger.go @@ -0,0 +1,138 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/domdebugger" + "github.com/chromedp/cdproto/runtime" +) + +// DOMDebugger executes a cdproto command under DOMDebugger domain. +type DOMDebugger struct { + ctxWithExecutor context.Context +} + +// GetEventListeners returns event listeners of the given object. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-getEventListeners +// +// parameters: +// - `objectID`: Identifier of the object to return listeners for. +// - `depth`: This can be nil. (Optional) The maximum depth at which Node children should be retrieved, defaults to 1. Use -1 for the entire subtree or provide an integer larger than 0. +// - `pierce`: This can be nil. (Optional) Whether or not iframes and shadow roots should be traversed when returning the subtree (default is false). Reports listeners for all contexts if pierce is enabled. +// +// returns: +// - `retListeners`: Array of relevant listeners. +func (doDOMDebugger DOMDebugger) GetEventListeners(objectID runtime.RemoteObjectID, depth *int64, pierce *bool) (retListeners []*domdebugger.EventListener, err error) { + b := domdebugger.GetEventListeners(objectID) + if depth != nil { + b = b.WithDepth(*depth) + } + if pierce != nil { + b = b.WithPierce(*pierce) + } + return b.Do(doDOMDebugger.ctxWithExecutor) +} + +// RemoveDOMBreakpoint removes DOM breakpoint that was set using +// setDOMBreakpoint. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-removeDOMBreakpoint +// +// parameters: +// - `nodeID`: Identifier of the node to remove breakpoint from. +// - `type`: Type of the breakpoint to remove. +func (doDOMDebugger DOMDebugger) RemoveDOMBreakpoint(nodeID cdp.NodeID, typeVal domdebugger.DOMBreakpointType) (err error) { + b := domdebugger.RemoveDOMBreakpoint(nodeID, typeVal) + return b.Do(doDOMDebugger.ctxWithExecutor) +} + +// RemoveEventListenerBreakpoint removes breakpoint on particular DOM event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-removeEventListenerBreakpoint +// +// parameters: +// - `eventName`: Event name. +// - `targetName`: This can be nil. (Optional) EventTarget interface name. +func (doDOMDebugger DOMDebugger) RemoveEventListenerBreakpoint(eventName string, targetName *string) (err error) { + b := domdebugger.RemoveEventListenerBreakpoint(eventName) + if targetName != nil { + b = b.WithTargetName(*targetName) + } + return b.Do(doDOMDebugger.ctxWithExecutor) +} + +// RemoveInstrumentationBreakpoint removes breakpoint on particular native +// event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-removeInstrumentationBreakpoint +// +// parameters: +// - `eventName`: Instrumentation name to stop on. +func (doDOMDebugger DOMDebugger) RemoveInstrumentationBreakpoint(eventName string) (err error) { + b := domdebugger.RemoveInstrumentationBreakpoint(eventName) + return b.Do(doDOMDebugger.ctxWithExecutor) +} + +// RemoveXHRBreakpoint removes breakpoint from XMLHttpRequest. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-removeXHRBreakpoint +// +// parameters: +// - `url`: Resource URL substring. +func (doDOMDebugger DOMDebugger) RemoveXHRBreakpoint(url string) (err error) { + b := domdebugger.RemoveXHRBreakpoint(url) + return b.Do(doDOMDebugger.ctxWithExecutor) +} + +// SetDOMBreakpoint sets breakpoint on particular operation with DOM. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-setDOMBreakpoint +// +// parameters: +// - `nodeID`: Identifier of the node to set breakpoint on. +// - `type`: Type of the operation to stop upon. +func (doDOMDebugger DOMDebugger) SetDOMBreakpoint(nodeID cdp.NodeID, typeVal domdebugger.DOMBreakpointType) (err error) { + b := domdebugger.SetDOMBreakpoint(nodeID, typeVal) + return b.Do(doDOMDebugger.ctxWithExecutor) +} + +// SetEventListenerBreakpoint sets breakpoint on particular DOM event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-setEventListenerBreakpoint +// +// parameters: +// - `eventName`: DOM Event name to stop on (any DOM event will do). +// - `targetName`: This can be nil. (Optional) EventTarget interface name to stop on. If equal to "*" or not provided, will stop on any EventTarget. +func (doDOMDebugger DOMDebugger) SetEventListenerBreakpoint(eventName string, targetName *string) (err error) { + b := domdebugger.SetEventListenerBreakpoint(eventName) + if targetName != nil { + b = b.WithTargetName(*targetName) + } + return b.Do(doDOMDebugger.ctxWithExecutor) +} + +// SetInstrumentationBreakpoint sets breakpoint on particular native event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-setInstrumentationBreakpoint +// +// parameters: +// - `eventName`: Instrumentation name to stop on. +func (doDOMDebugger DOMDebugger) SetInstrumentationBreakpoint(eventName string) (err error) { + b := domdebugger.SetInstrumentationBreakpoint(eventName) + return b.Do(doDOMDebugger.ctxWithExecutor) +} + +// SetXHRBreakpoint sets breakpoint on XMLHttpRequest. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMDebugger#method-setXHRBreakpoint +// +// parameters: +// - `url`: Resource URL substring. All XHRs having this substring in the URL will get stopped upon. +func (doDOMDebugger DOMDebugger) SetXHRBreakpoint(url string) (err error) { + b := domdebugger.SetXHRBreakpoint(url) + return b.Do(doDOMDebugger.ctxWithExecutor) +} diff --git a/domain/domsnapshot.go b/domain/domsnapshot.go new file mode 100644 index 0000000..bebb168 --- /dev/null +++ b/domain/domsnapshot.go @@ -0,0 +1,57 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/domsnapshot" +) + +// DOMSnapshot executes a cdproto command under DOMSnapshot domain. +type DOMSnapshot struct { + ctxWithExecutor context.Context +} + +// Disable disables DOM snapshot agent for the given page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMSnapshot#method-disable +func (doDOMSnapshot DOMSnapshot) Disable() (err error) { + b := domsnapshot.Disable() + return b.Do(doDOMSnapshot.ctxWithExecutor) +} + +// Enable enables DOM snapshot agent for the given page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMSnapshot#method-enable +func (doDOMSnapshot DOMSnapshot) Enable() (err error) { + b := domsnapshot.Enable() + return b.Do(doDOMSnapshot.ctxWithExecutor) +} + +// CaptureSnapshot returns a document snapshot, including the full DOM tree +// of the root node (including iframes, template contents, and imported +// documents) in a flattened array, as well as layout and white-listed computed +// style information for the nodes. Shadow DOM in the returned DOM tree is +// flattened. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMSnapshot#method-captureSnapshot +// +// parameters: +// - `computedStyles`: Whitelist of computed styles to return. +// - `includePaintOrder`: This can be nil. (Optional) Whether to include layout object paint orders into the snapshot. +// - `includeDOMRects`: This can be nil. (Optional) Whether to include DOM rectangles (offsetRects, clientRects, scrollRects) into the snapshot +// +// returns: +// - `retDocuments`: The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document. +// - `retStrings`: Shared string table that all string properties refer to with indexes. +func (doDOMSnapshot DOMSnapshot) CaptureSnapshot(computedStyles []string, includePaintOrder *bool, includeDOMRects *bool) (retDocuments []*domsnapshot.DocumentSnapshot, retStrings []string, err error) { + b := domsnapshot.CaptureSnapshot(computedStyles) + if includePaintOrder != nil { + b = b.WithIncludePaintOrder(*includePaintOrder) + } + if includeDOMRects != nil { + b = b.WithIncludeDOMRects(*includeDOMRects) + } + return b.Do(doDOMSnapshot.ctxWithExecutor) +} diff --git a/domain/domstorage.go b/domain/domstorage.go new file mode 100644 index 0000000..351aec9 --- /dev/null +++ b/domain/domstorage.go @@ -0,0 +1,82 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/domstorage" +) + +// DOMStorage executes a cdproto command under DOMStorage domain. +type DOMStorage struct { + ctxWithExecutor context.Context +} + +// Clear [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-clear +// +// parameters: +// - `storageID` +func (doDOMStorage DOMStorage) Clear(storageID *domstorage.StorageID) (err error) { + b := domstorage.Clear(storageID) + return b.Do(doDOMStorage.ctxWithExecutor) +} + +// Disable disables storage tracking, prevents storage events from being sent +// to the client. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-disable +func (doDOMStorage DOMStorage) Disable() (err error) { + b := domstorage.Disable() + return b.Do(doDOMStorage.ctxWithExecutor) +} + +// Enable enables storage tracking, storage events will now be delivered to +// the client. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-enable +func (doDOMStorage DOMStorage) Enable() (err error) { + b := domstorage.Enable() + return b.Do(doDOMStorage.ctxWithExecutor) +} + +// GetDOMStorageItems [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-getDOMStorageItems +// +// parameters: +// - `storageID` +// +// returns: +// - `retEntries` +func (doDOMStorage DOMStorage) GetDOMStorageItems(storageID *domstorage.StorageID) (retEntries []domstorage.Item, err error) { + b := domstorage.GetDOMStorageItems(storageID) + return b.Do(doDOMStorage.ctxWithExecutor) +} + +// RemoveDOMStorageItem [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-removeDOMStorageItem +// +// parameters: +// - `storageID` +// - `key` +func (doDOMStorage DOMStorage) RemoveDOMStorageItem(storageID *domstorage.StorageID, key string) (err error) { + b := domstorage.RemoveDOMStorageItem(storageID, key) + return b.Do(doDOMStorage.ctxWithExecutor) +} + +// SetDOMStorageItem [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#method-setDOMStorageItem +// +// parameters: +// - `storageID` +// - `key` +// - `value` +func (doDOMStorage DOMStorage) SetDOMStorageItem(storageID *domstorage.StorageID, key string, value string) (err error) { + b := domstorage.SetDOMStorageItem(storageID, key, value) + return b.Do(doDOMStorage.ctxWithExecutor) +} diff --git a/domain/emulation.go b/domain/emulation.go new file mode 100644 index 0000000..ab0a1cd --- /dev/null +++ b/domain/emulation.go @@ -0,0 +1,321 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/emulation" + "github.com/chromedp/cdproto/page" +) + +// Emulation executes a cdproto command under Emulation domain. +type Emulation struct { + ctxWithExecutor context.Context +} + +// CanEmulate tells whether emulation is supported. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-canEmulate +// +// returns: +// - `retResult`: True if emulation is supported. +func (doEmulation Emulation) CanEmulate() (retResult bool, err error) { + b := emulation.CanEmulate() + return b.Do(doEmulation.ctxWithExecutor) +} + +// ClearDeviceMetricsOverride clears the overridden device metrics. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-clearDeviceMetricsOverride +func (doEmulation Emulation) ClearDeviceMetricsOverride() (err error) { + b := emulation.ClearDeviceMetricsOverride() + return b.Do(doEmulation.ctxWithExecutor) +} + +// ClearGeolocationOverride clears the overridden Geolocation Position and +// Error. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-clearGeolocationOverride +func (doEmulation Emulation) ClearGeolocationOverride() (err error) { + b := emulation.ClearGeolocationOverride() + return b.Do(doEmulation.ctxWithExecutor) +} + +// ResetPageScaleFactor requests that page scale factor is reset to initial +// values. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-resetPageScaleFactor +func (doEmulation Emulation) ResetPageScaleFactor() (err error) { + b := emulation.ResetPageScaleFactor() + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetFocusEmulationEnabled enables or disables simulating a focused and +// active page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setFocusEmulationEnabled +// +// parameters: +// - `enabled`: Whether to enable to disable focus emulation. +func (doEmulation Emulation) SetFocusEmulationEnabled(enabled bool) (err error) { + b := emulation.SetFocusEmulationEnabled(enabled) + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetCPUThrottlingRate enables CPU throttling to emulate slow CPUs. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setCPUThrottlingRate +// +// parameters: +// - `rate`: Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc). +func (doEmulation Emulation) SetCPUThrottlingRate(rate float64) (err error) { + b := emulation.SetCPUThrottlingRate(rate) + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetDefaultBackgroundColorOverride sets or clears an override of the +// default background color of the frame. This override is used if the content +// does not specify one. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDefaultBackgroundColorOverride +// +// parameters: +// - `color`: This can be nil. (Optional) RGBA of the default background color. If not specified, any existing override will be cleared. +func (doEmulation Emulation) SetDefaultBackgroundColorOverride(color *cdp.RGBA) (err error) { + b := emulation.SetDefaultBackgroundColorOverride() + if color != nil { + b = b.WithColor(color) + } + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetDeviceMetricsOverride overrides the values of device screen dimensions +// (window.screen.width, window.screen.height, window.innerWidth, +// window.innerHeight, and "device-width"/"device-height"-related CSS media +// query results). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDeviceMetricsOverride +// +// parameters: +// - `width`: Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override. +// - `height`: Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override. +// - `deviceScaleFactor`: Overriding device scale factor value. 0 disables the override. +// - `mobile`: Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text autosizing and more. +// - `scale`: This can be nil. (Optional) Scale to apply to resulting view image. +// - `screenWidth`: This can be nil. (Optional) Overriding screen width value in pixels (minimum 0, maximum 10000000). +// - `screenHeight`: This can be nil. (Optional) Overriding screen height value in pixels (minimum 0, maximum 10000000). +// - `positionX`: This can be nil. (Optional) Overriding view X position on screen in pixels (minimum 0, maximum 10000000). +// - `positionY`: This can be nil. (Optional) Overriding view Y position on screen in pixels (minimum 0, maximum 10000000). +// - `dontSetVisibleSize`: This can be nil. (Optional) Do not set visible view size, rely upon explicit setVisibleSize call. +// - `screenOrientation`: This can be nil. (Optional) Screen orientation override. +// - `viewport`: This can be nil. (Optional) If set, the visible area of the page will be overridden to this viewport. This viewport change is not observed by the page, e.g. viewport-relative elements do not change positions. +func (doEmulation Emulation) SetDeviceMetricsOverride(width int64, height int64, deviceScaleFactor float64, mobile bool, scale *float64, screenWidth *int64, screenHeight *int64, positionX *int64, positionY *int64, dontSetVisibleSize *bool, screenOrientation *emulation.ScreenOrientation, viewport *page.Viewport) (err error) { + b := emulation.SetDeviceMetricsOverride(width, height, deviceScaleFactor, mobile) + if scale != nil { + b = b.WithScale(*scale) + } + if screenWidth != nil { + b = b.WithScreenWidth(*screenWidth) + } + if screenHeight != nil { + b = b.WithScreenHeight(*screenHeight) + } + if positionX != nil { + b = b.WithPositionX(*positionX) + } + if positionY != nil { + b = b.WithPositionY(*positionY) + } + if dontSetVisibleSize != nil { + b = b.WithDontSetVisibleSize(*dontSetVisibleSize) + } + if screenOrientation != nil { + b = b.WithScreenOrientation(screenOrientation) + } + if viewport != nil { + b = b.WithViewport(viewport) + } + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetScrollbarsHidden [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setScrollbarsHidden +// +// parameters: +// - `hidden`: Whether scrollbars should be always hidden. +func (doEmulation Emulation) SetScrollbarsHidden(hidden bool) (err error) { + b := emulation.SetScrollbarsHidden(hidden) + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetDocumentCookieDisabled [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setDocumentCookieDisabled +// +// parameters: +// - `disabled`: Whether document.coookie API should be disabled. +func (doEmulation Emulation) SetDocumentCookieDisabled(disabled bool) (err error) { + b := emulation.SetDocumentCookieDisabled(disabled) + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetEmitTouchEventsForMouse [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setEmitTouchEventsForMouse +// +// parameters: +// - `enabled`: Whether touch emulation based on mouse input should be enabled. +// - `configuration`: This can be nil. (Optional) Touch/gesture events configuration. Default: current platform. +func (doEmulation Emulation) SetEmitTouchEventsForMouse(enabled bool, configuration *emulation.SetEmitTouchEventsForMouseConfiguration) (err error) { + b := emulation.SetEmitTouchEventsForMouse(enabled) + if configuration != nil { + b = b.WithConfiguration(*configuration) + } + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetEmulatedMedia emulates the given media type or media feature for CSS +// media queries. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setEmulatedMedia +// +// parameters: +// - `media`: This can be nil. (Optional) Media type to emulate. Empty string disables the override. +// - `features`: This can be nil. (Optional) Media features to emulate. +func (doEmulation Emulation) SetEmulatedMedia(media *string, features []*emulation.MediaFeature) (err error) { + b := emulation.SetEmulatedMedia() + if media != nil { + b = b.WithMedia(*media) + } + if features != nil { + b = b.WithFeatures(features) + } + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetGeolocationOverride overrides the Geolocation Position or Error. +// Omitting any of the parameters emulates position unavailable. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setGeolocationOverride +// +// parameters: +// - `latitude`: This can be nil. (Optional) Mock latitude +// - `longitude`: This can be nil. (Optional) Mock longitude +// - `accuracy`: This can be nil. (Optional) Mock accuracy +func (doEmulation Emulation) SetGeolocationOverride(latitude *float64, longitude *float64, accuracy *float64) (err error) { + b := emulation.SetGeolocationOverride() + if latitude != nil { + b = b.WithLatitude(*latitude) + } + if longitude != nil { + b = b.WithLongitude(*longitude) + } + if accuracy != nil { + b = b.WithAccuracy(*accuracy) + } + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetPageScaleFactor sets a specified page scale factor. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setPageScaleFactor +// +// parameters: +// - `pageScaleFactor`: Page scale factor. +func (doEmulation Emulation) SetPageScaleFactor(pageScaleFactor float64) (err error) { + b := emulation.SetPageScaleFactor(pageScaleFactor) + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetScriptExecutionDisabled switches script execution in the page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setScriptExecutionDisabled +// +// parameters: +// - `value`: Whether script execution should be disabled in the page. +func (doEmulation Emulation) SetScriptExecutionDisabled(value bool) (err error) { + b := emulation.SetScriptExecutionDisabled(value) + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetTouchEmulationEnabled enables touch on platforms which do not support +// them. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setTouchEmulationEnabled +// +// parameters: +// - `enabled`: Whether the touch event emulation should be enabled. +// - `maxTouchPoints`: This can be nil. (Optional) Maximum touch points supported. Defaults to one. +func (doEmulation Emulation) SetTouchEmulationEnabled(enabled bool, maxTouchPoints *int64) (err error) { + b := emulation.SetTouchEmulationEnabled(enabled) + if maxTouchPoints != nil { + b = b.WithMaxTouchPoints(*maxTouchPoints) + } + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetVirtualTimePolicy turns on virtual time for all frames (replacing +// real-time with a synthetic time source) and sets the current virtual time +// policy. Note this supersedes any previous time budget. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setVirtualTimePolicy +// +// parameters: +// - `policy` +// - `budget`: This can be nil. (Optional) If set, after this many virtual milliseconds have elapsed virtual time will be paused and a virtualTimeBudgetExpired event is sent. +// - `maxVirtualTimeTaskStarvationCount`: This can be nil. (Optional) If set this specifies the maximum number of tasks that can be run before virtual is forced forwards to prevent deadlock. +// - `waitForNavigation`: This can be nil. (Optional) If set the virtual time policy change should be deferred until any frame starts navigating. Note any previous deferred policy change is superseded. +// - `initialVirtualTime`: This can be nil. (Optional) If set, base::Time::Now will be overridden to initially return this value. +// +// returns: +// - `retVirtualTimeTicksBase`: Absolute timestamp at which virtual time was first enabled (up time in milliseconds). +func (doEmulation Emulation) SetVirtualTimePolicy(policy emulation.VirtualTimePolicy, budget *float64, maxVirtualTimeTaskStarvationCount *int64, waitForNavigation *bool, initialVirtualTime *cdp.TimeSinceEpoch) (retVirtualTimeTicksBase float64, err error) { + b := emulation.SetVirtualTimePolicy(policy) + if budget != nil { + b = b.WithBudget(*budget) + } + if maxVirtualTimeTaskStarvationCount != nil { + b = b.WithMaxVirtualTimeTaskStarvationCount(*maxVirtualTimeTaskStarvationCount) + } + if waitForNavigation != nil { + b = b.WithWaitForNavigation(*waitForNavigation) + } + if initialVirtualTime != nil { + b = b.WithInitialVirtualTime(initialVirtualTime) + } + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetTimezoneOverride overrides default host system timezone with the +// specified one. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setTimezoneOverride +// +// parameters: +// - `timezoneID`: The timezone identifier. If empty, disables the override and restores default host system timezone. +func (doEmulation Emulation) SetTimezoneOverride(timezoneID string) (err error) { + b := emulation.SetTimezoneOverride(timezoneID) + return b.Do(doEmulation.ctxWithExecutor) +} + +// SetUserAgentOverride allows overriding user agent with the given string. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Emulation#method-setUserAgentOverride +// +// parameters: +// - `userAgent`: User agent to use. +// - `acceptLanguage`: This can be nil. (Optional) Browser langugage to emulate. +// - `platform`: This can be nil. (Optional) The platform navigator.platform should return. +func (doEmulation Emulation) SetUserAgentOverride(userAgent string, acceptLanguage *string, platform *string) (err error) { + b := emulation.SetUserAgentOverride(userAgent) + if acceptLanguage != nil { + b = b.WithAcceptLanguage(*acceptLanguage) + } + if platform != nil { + b = b.WithPlatform(*platform) + } + return b.Do(doEmulation.ctxWithExecutor) +} diff --git a/domain/fetch.go b/domain/fetch.go new file mode 100644 index 0000000..57ce158 --- /dev/null +++ b/domain/fetch.go @@ -0,0 +1,165 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/fetch" + "github.com/chromedp/cdproto/io" + "github.com/chromedp/cdproto/network" +) + +// Fetch executes a cdproto command under Fetch domain. +type Fetch struct { + ctxWithExecutor context.Context +} + +// Disable disables the fetch domain. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-disable +func (doFetch Fetch) Disable() (err error) { + b := fetch.Disable() + return b.Do(doFetch.ctxWithExecutor) +} + +// Enable enables issuing of requestPaused events. A request will be paused +// until client calls one of failRequest, fulfillRequest or +// continueRequest/continueWithAuth. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-enable +// +// parameters: +// - `patterns`: This can be nil. (Optional) If specified, only requests matching any of these patterns will produce fetchRequested event and will be paused until clients response. If not set, all requests will be affected. +// - `handleAuthRequests`: This can be nil. (Optional) If true, authRequired events will be issued and requests will be paused expecting a call to continueWithAuth. +func (doFetch Fetch) Enable(patterns []*fetch.RequestPattern, handleAuthRequests *bool) (err error) { + b := fetch.Enable() + if patterns != nil { + b = b.WithPatterns(patterns) + } + if handleAuthRequests != nil { + b = b.WithHandleAuthRequests(*handleAuthRequests) + } + return b.Do(doFetch.ctxWithExecutor) +} + +// FailRequest causes the request to fail with specified reason. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-failRequest +// +// parameters: +// - `requestID`: An id the client received in requestPaused event. +// - `errorReason`: Causes the request to fail with the given reason. +func (doFetch Fetch) FailRequest(requestID fetch.RequestID, errorReason network.ErrorReason) (err error) { + b := fetch.FailRequest(requestID, errorReason) + return b.Do(doFetch.ctxWithExecutor) +} + +// FulfillRequest provides response to the request. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-fulfillRequest +// +// parameters: +// - `requestID`: An id the client received in requestPaused event. +// - `responseCode`: An HTTP response code. +// - `responseHeaders`: This can be nil. (Optional) Response headers. +// - `binaryResponseHeaders`: This can be nil. (Optional) Alternative way of specifying response headers as a \0-separated series of name: value pairs. Prefer the above method unless you need to represent some non-UTF8 values that can't be transmitted over the protocol as text. +// - `body`: This can be nil. (Optional) A response body. +// - `responsePhrase`: This can be nil. (Optional) A textual representation of responseCode. If absent, a standard phrase matching responseCode is used. +func (doFetch Fetch) FulfillRequest(requestID fetch.RequestID, responseCode int64, responseHeaders []*fetch.HeaderEntry, binaryResponseHeaders *string, body *string, responsePhrase *string) (err error) { + b := fetch.FulfillRequest(requestID, responseCode) + if responseHeaders != nil { + b = b.WithResponseHeaders(responseHeaders) + } + if binaryResponseHeaders != nil { + b = b.WithBinaryResponseHeaders(*binaryResponseHeaders) + } + if body != nil { + b = b.WithBody(*body) + } + if responsePhrase != nil { + b = b.WithResponsePhrase(*responsePhrase) + } + return b.Do(doFetch.ctxWithExecutor) +} + +// ContinueRequest continues the request, optionally modifying some of its +// parameters. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-continueRequest +// +// parameters: +// - `requestID`: An id the client received in requestPaused event. +// - `url`: This can be nil. (Optional) If set, the request url will be modified in a way that's not observable by page. +// - `method`: This can be nil. (Optional) If set, the request method is overridden. +// - `postData`: This can be nil. (Optional) If set, overrides the post data in the request. +// - `headers`: This can be nil. (Optional) If set, overrides the request headrts. +func (doFetch Fetch) ContinueRequest(requestID fetch.RequestID, url *string, method *string, postData *string, headers []*fetch.HeaderEntry) (err error) { + b := fetch.ContinueRequest(requestID) + if url != nil { + b = b.WithURL(*url) + } + if method != nil { + b = b.WithMethod(*method) + } + if postData != nil { + b = b.WithPostData(*postData) + } + if headers != nil { + b = b.WithHeaders(headers) + } + return b.Do(doFetch.ctxWithExecutor) +} + +// ContinueWithAuth continues a request supplying authChallengeResponse +// following authRequired event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-continueWithAuth +// +// parameters: +// - `requestID`: An id the client received in authRequired event. +// - `authChallengeResponse`: Response to with an authChallenge. +func (doFetch Fetch) ContinueWithAuth(requestID fetch.RequestID, authChallengeResponse *fetch.AuthChallengeResponse) (err error) { + b := fetch.ContinueWithAuth(requestID, authChallengeResponse) + return b.Do(doFetch.ctxWithExecutor) +} + +// GetResponseBody causes the body of the response to be received from the +// server and returned as a single string. May only be issued for a request that +// is paused in the Response stage and is mutually exclusive with +// takeResponseBodyForInterceptionAsStream. Calling other methods that affect +// the request or disabling fetch domain before body is received results in an +// undefined behavior. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-getResponseBody +// +// parameters: +// - `requestID`: Identifier for the intercepted request to get body for. +// +// returns: +// - `retBody`: Response body. +func (doFetch Fetch) GetResponseBody(requestID fetch.RequestID) (retBody []byte, err error) { + b := fetch.GetResponseBody(requestID) + return b.Do(doFetch.ctxWithExecutor) +} + +// TakeResponseBodyAsStream returns a handle to the stream representing the +// response body. The request must be paused in the HeadersReceived stage. Note +// that after this command the request can't be continued as is -- client either +// needs to cancel it or to provide the response body. The stream only supports +// sequential read, IO.read will fail if the position is specified. This method +// is mutually exclusive with getResponseBody. Calling other methods that affect +// the request or disabling fetch domain before body is received results in an +// undefined behavior. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Fetch#method-takeResponseBodyAsStream +// +// parameters: +// - `requestID` +// +// returns: +// - `retStream` +func (doFetch Fetch) TakeResponseBodyAsStream(requestID fetch.RequestID) (retStream io.StreamHandle, err error) { + b := fetch.TakeResponseBodyAsStream(requestID) + return b.Do(doFetch.ctxWithExecutor) +} diff --git a/domain/har.go b/domain/har.go new file mode 100644 index 0000000..9351280 --- /dev/null +++ b/domain/har.go @@ -0,0 +1,12 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" +) + +// HAR executes a cdproto command under HAR domain. +type HAR struct { + ctxWithExecutor context.Context +} diff --git a/domain/headlessexperimental.go b/domain/headlessexperimental.go new file mode 100644 index 0000000..c97c083 --- /dev/null +++ b/domain/headlessexperimental.go @@ -0,0 +1,64 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/headlessexperimental" +) + +// HeadlessExperimental executes a cdproto command under HeadlessExperimental domain. +type HeadlessExperimental struct { + ctxWithExecutor context.Context +} + +// BeginFrame sends a BeginFrame to the target and returns when the frame was +// completed. Optionally captures a screenshot from the resulting frame. +// Requires that the target was created with enabled BeginFrameControl. Designed +// for use with --run-all-compositor-stages-before-draw, see also +// https://goo.gl/3zHXhB for more background. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeadlessExperimental#method-beginFrame +// +// parameters: +// - `frameTimeTicks`: This can be nil. (Optional) Timestamp of this BeginFrame in Renderer TimeTicks (milliseconds of uptime). If not set, the current time will be used. +// - `interval`: This can be nil. (Optional) The interval between BeginFrames that is reported to the compositor, in milliseconds. Defaults to a 60 frames/second interval, i.e. about 16.666 milliseconds. +// - `noDisplayUpdates`: This can be nil. (Optional) Whether updates should not be committed and drawn onto the display. False by default. If true, only side effects of the BeginFrame will be run, such as layout and animations, but any visual updates may not be visible on the display or in screenshots. +// - `screenshot`: This can be nil. (Optional) If set, a screenshot of the frame will be captured and returned in the response. Otherwise, no screenshot will be captured. Note that capturing a screenshot can fail, for example, during renderer initialization. In such a case, no screenshot data will be returned. +// +// returns: +// - `retHasDamage`: Whether the BeginFrame resulted in damage and, thus, a new frame was committed to the display. Reported for diagnostic uses, may be removed in the future. +// - `retScreenshotData`: Base64-encoded image data of the screenshot, if one was requested and successfully taken. +func (doHeadlessExperimental HeadlessExperimental) BeginFrame(frameTimeTicks *float64, interval *float64, noDisplayUpdates *bool, screenshot *headlessexperimental.ScreenshotParams) (retHasDamage bool, retScreenshotData []byte, err error) { + b := headlessexperimental.BeginFrame() + if frameTimeTicks != nil { + b = b.WithFrameTimeTicks(*frameTimeTicks) + } + if interval != nil { + b = b.WithInterval(*interval) + } + if noDisplayUpdates != nil { + b = b.WithNoDisplayUpdates(*noDisplayUpdates) + } + if screenshot != nil { + b = b.WithScreenshot(screenshot) + } + return b.Do(doHeadlessExperimental.ctxWithExecutor) +} + +// Disable disables headless events for the target. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeadlessExperimental#method-disable +func (doHeadlessExperimental HeadlessExperimental) Disable() (err error) { + b := headlessexperimental.Disable() + return b.Do(doHeadlessExperimental.ctxWithExecutor) +} + +// Enable enables headless events for the target. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeadlessExperimental#method-enable +func (doHeadlessExperimental HeadlessExperimental) Enable() (err error) { + b := headlessexperimental.Enable() + return b.Do(doHeadlessExperimental.ctxWithExecutor) +} diff --git a/domain/heapprofiler.go b/domain/heapprofiler.go new file mode 100644 index 0000000..1522b5c --- /dev/null +++ b/domain/heapprofiler.go @@ -0,0 +1,161 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/heapprofiler" + "github.com/chromedp/cdproto/runtime" +) + +// HeapProfiler executes a cdproto command under HeapProfiler domain. +type HeapProfiler struct { + ctxWithExecutor context.Context +} + +// AddInspectedHeapObject enables console to refer to the node with given id +// via $x (see Command Line API for more details $x functions). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-addInspectedHeapObject +// +// parameters: +// - `heapObjectID`: Heap snapshot object id to be accessible by means of $x command line API. +func (doHeapProfiler HeapProfiler) AddInspectedHeapObject(heapObjectID heapprofiler.HeapSnapshotObjectID) (err error) { + b := heapprofiler.AddInspectedHeapObject(heapObjectID) + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// CollectGarbage [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-collectGarbage +func (doHeapProfiler HeapProfiler) CollectGarbage() (err error) { + b := heapprofiler.CollectGarbage() + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// Disable [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-disable +func (doHeapProfiler HeapProfiler) Disable() (err error) { + b := heapprofiler.Disable() + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// Enable [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-enable +func (doHeapProfiler HeapProfiler) Enable() (err error) { + b := heapprofiler.Enable() + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// GetHeapObjectID [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-getHeapObjectId +// +// parameters: +// - `objectID`: Identifier of the object to get heap object id for. +// +// returns: +// - `retHeapSnapshotObjectID`: Id of the heap snapshot object corresponding to the passed remote object id. +func (doHeapProfiler HeapProfiler) GetHeapObjectID(objectID runtime.RemoteObjectID) (retHeapSnapshotObjectID heapprofiler.HeapSnapshotObjectID, err error) { + b := heapprofiler.GetHeapObjectID(objectID) + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// GetObjectByHeapObjectID [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-getObjectByHeapObjectId +// +// parameters: +// - `objectID` +// - `objectGroup`: This can be nil. (Optional) Symbolic group name that can be used to release multiple objects. +// +// returns: +// - `retResult`: Evaluation result. +func (doHeapProfiler HeapProfiler) GetObjectByHeapObjectID(objectID heapprofiler.HeapSnapshotObjectID, objectGroup *string) (retResult *runtime.RemoteObject, err error) { + b := heapprofiler.GetObjectByHeapObjectID(objectID) + if objectGroup != nil { + b = b.WithObjectGroup(*objectGroup) + } + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// GetSamplingProfile [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-getSamplingProfile +// +// returns: +// - `retProfile`: Return the sampling profile being collected. +func (doHeapProfiler HeapProfiler) GetSamplingProfile() (retProfile *heapprofiler.SamplingHeapProfile, err error) { + b := heapprofiler.GetSamplingProfile() + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// StartSampling [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-startSampling +// +// parameters: +// - `samplingInterval`: This can be nil. (Optional) Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. +func (doHeapProfiler HeapProfiler) StartSampling(samplingInterval *float64) (err error) { + b := heapprofiler.StartSampling() + if samplingInterval != nil { + b = b.WithSamplingInterval(*samplingInterval) + } + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// StartTrackingHeapObjects [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-startTrackingHeapObjects +// +// parameters: +// - `trackAllocations` +func (doHeapProfiler HeapProfiler) StartTrackingHeapObjects(trackAllocations *bool) (err error) { + b := heapprofiler.StartTrackingHeapObjects() + if trackAllocations != nil { + b = b.WithTrackAllocations(*trackAllocations) + } + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// StopSampling [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-stopSampling +// +// returns: +// - `retProfile`: Recorded sampling heap profile. +func (doHeapProfiler HeapProfiler) StopSampling() (retProfile *heapprofiler.SamplingHeapProfile, err error) { + b := heapprofiler.StopSampling() + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// StopTrackingHeapObjects [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-stopTrackingHeapObjects +// +// parameters: +// - `reportProgress`: This can be nil. (Optional) If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. +func (doHeapProfiler HeapProfiler) StopTrackingHeapObjects(reportProgress *bool) (err error) { + b := heapprofiler.StopTrackingHeapObjects() + if reportProgress != nil { + b = b.WithReportProgress(*reportProgress) + } + return b.Do(doHeapProfiler.ctxWithExecutor) +} + +// TakeHeapSnapshot [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/HeapProfiler#method-takeHeapSnapshot +// +// parameters: +// - `reportProgress`: This can be nil. (Optional) If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. +func (doHeapProfiler HeapProfiler) TakeHeapSnapshot(reportProgress *bool) (err error) { + b := heapprofiler.TakeHeapSnapshot() + if reportProgress != nil { + b = b.WithReportProgress(*reportProgress) + } + return b.Do(doHeapProfiler.ctxWithExecutor) +} diff --git a/domain/indexeddb.go b/domain/indexeddb.go new file mode 100644 index 0000000..ae06d6f --- /dev/null +++ b/domain/indexeddb.go @@ -0,0 +1,139 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/indexeddb" +) + +// IndexedDB executes a cdproto command under IndexedDB domain. +type IndexedDB struct { + ctxWithExecutor context.Context +} + +// ClearObjectStore clears all entries from an object store. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-clearObjectStore +// +// parameters: +// - `securityOrigin`: Security origin. +// - `databaseName`: Database name. +// - `objectStoreName`: Object store name. +func (doIndexedDB IndexedDB) ClearObjectStore(securityOrigin string, databaseName string, objectStoreName string) (err error) { + b := indexeddb.ClearObjectStore(securityOrigin, databaseName, objectStoreName) + return b.Do(doIndexedDB.ctxWithExecutor) +} + +// DeleteDatabase deletes a database. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-deleteDatabase +// +// parameters: +// - `securityOrigin`: Security origin. +// - `databaseName`: Database name. +func (doIndexedDB IndexedDB) DeleteDatabase(securityOrigin string, databaseName string) (err error) { + b := indexeddb.DeleteDatabase(securityOrigin, databaseName) + return b.Do(doIndexedDB.ctxWithExecutor) +} + +// DeleteObjectStoreEntries delete a range of entries from an object store. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-deleteObjectStoreEntries +// +// parameters: +// - `securityOrigin` +// - `databaseName` +// - `objectStoreName` +// - `keyRange`: Range of entry keys to delete +func (doIndexedDB IndexedDB) DeleteObjectStoreEntries(securityOrigin string, databaseName string, objectStoreName string, keyRange *indexeddb.KeyRange) (err error) { + b := indexeddb.DeleteObjectStoreEntries(securityOrigin, databaseName, objectStoreName, keyRange) + return b.Do(doIndexedDB.ctxWithExecutor) +} + +// Disable disables events from backend. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-disable +func (doIndexedDB IndexedDB) Disable() (err error) { + b := indexeddb.Disable() + return b.Do(doIndexedDB.ctxWithExecutor) +} + +// Enable enables events from backend. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-enable +func (doIndexedDB IndexedDB) Enable() (err error) { + b := indexeddb.Enable() + return b.Do(doIndexedDB.ctxWithExecutor) +} + +// RequestData requests data from object store or index. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-requestData +// +// parameters: +// - `securityOrigin`: Security origin. +// - `databaseName`: Database name. +// - `objectStoreName`: Object store name. +// - `indexName`: Index name, empty string for object store data requests. +// - `skipCount`: Number of records to skip. +// - `pageSize`: Number of records to fetch. +// - `keyRange`: This can be nil. (Optional) Key range. +// +// returns: +// - `retObjectStoreDataEntries`: Array of object store data entries. +// - `retHasMore`: If true, there are more entries to fetch in the given range. +func (doIndexedDB IndexedDB) RequestData(securityOrigin string, databaseName string, objectStoreName string, indexName string, skipCount int64, pageSize int64, keyRange *indexeddb.KeyRange) (retObjectStoreDataEntries []*indexeddb.DataEntry, retHasMore bool, err error) { + b := indexeddb.RequestData(securityOrigin, databaseName, objectStoreName, indexName, skipCount, pageSize) + if keyRange != nil { + b = b.WithKeyRange(keyRange) + } + return b.Do(doIndexedDB.ctxWithExecutor) +} + +// GetMetadata gets metadata of an object store. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-getMetadata +// +// parameters: +// - `securityOrigin`: Security origin. +// - `databaseName`: Database name. +// - `objectStoreName`: Object store name. +// +// returns: +// - `retEntriesCount`: the entries count +// - `retKeyGeneratorValue`: the current value of key generator, to become the next inserted key into the object store. Valid if objectStore.autoIncrement is true. +func (doIndexedDB IndexedDB) GetMetadata(securityOrigin string, databaseName string, objectStoreName string) (retEntriesCount float64, retKeyGeneratorValue float64, err error) { + b := indexeddb.GetMetadata(securityOrigin, databaseName, objectStoreName) + return b.Do(doIndexedDB.ctxWithExecutor) +} + +// RequestDatabase requests database with given name in given frame. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-requestDatabase +// +// parameters: +// - `securityOrigin`: Security origin. +// - `databaseName`: Database name. +// +// returns: +// - `retDatabaseWithObjectStores`: Database with an array of object stores. +func (doIndexedDB IndexedDB) RequestDatabase(securityOrigin string, databaseName string) (retDatabaseWithObjectStores *indexeddb.DatabaseWithObjectStores, err error) { + b := indexeddb.RequestDatabase(securityOrigin, databaseName) + return b.Do(doIndexedDB.ctxWithExecutor) +} + +// RequestDatabaseNames requests database names for given security origin. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IndexedDB#method-requestDatabaseNames +// +// parameters: +// - `securityOrigin`: Security origin. +// +// returns: +// - `retDatabaseNames`: Database names for origin. +func (doIndexedDB IndexedDB) RequestDatabaseNames(securityOrigin string) (retDatabaseNames []string, err error) { + b := indexeddb.RequestDatabaseNames(securityOrigin) + return b.Do(doIndexedDB.ctxWithExecutor) +} diff --git a/domain/input.go b/domain/input.go new file mode 100644 index 0000000..f9b639d --- /dev/null +++ b/domain/input.go @@ -0,0 +1,300 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/input" +) + +// Input executes a cdproto command under Input domain. +type Input struct { + ctxWithExecutor context.Context +} + +// DispatchKeyEvent dispatches a key event to the page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchKeyEvent +// +// parameters: +// - `type`: Type of the key event. +// - `modifiers`: This can be nil. (Optional) Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). +// - `timestamp`: This can be nil. (Optional) Time at which the event occurred. +// - `text`: This can be nil. (Optional) Text as generated by processing a virtual key code with a keyboard layout. Not needed for for keyUp and rawKeyDown events (default: "") +// - `unmodifiedText`: This can be nil. (Optional) Text that would have been generated by the keyboard if no modifiers were pressed (except for shift). Useful for shortcut (accelerator) key handling (default: ""). +// - `keyIdentifier`: This can be nil. (Optional) Unique key identifier (e.g., 'U+0041') (default: ""). +// - `code`: This can be nil. (Optional) Unique DOM defined string value for each physical key (e.g., 'KeyA') (default: ""). +// - `key`: This can be nil. (Optional) Unique DOM defined string value describing the meaning of the key in the context of active modifiers, keyboard layout, etc (e.g., 'AltGr') (default: ""). +// - `windowsVirtualKeyCode`: This can be nil. (Optional) Windows virtual key code (default: 0). +// - `nativeVirtualKeyCode`: This can be nil. (Optional) Native virtual key code (default: 0). +// - `autoRepeat`: This can be nil. (Optional) Whether the event was generated from auto repeat (default: false). +// - `isKeypad`: This can be nil. (Optional) Whether the event was generated from the keypad (default: false). +// - `isSystemKey`: This can be nil. (Optional) Whether the event was a system key event (default: false). +// - `location`: This can be nil. (Optional) Whether the event was from the left or right side of the keyboard. 1=Left, 2=Right (default: 0). +func (doInput Input) DispatchKeyEvent(typeVal input.KeyType, modifiers *input.Modifier, timestamp *input.TimeSinceEpoch, text *string, unmodifiedText *string, keyIdentifier *string, code *string, key *string, windowsVirtualKeyCode *int64, nativeVirtualKeyCode *int64, autoRepeat *bool, isKeypad *bool, isSystemKey *bool, location *int64) (err error) { + b := input.DispatchKeyEvent(typeVal) + if modifiers != nil { + b = b.WithModifiers(*modifiers) + } + if timestamp != nil { + b = b.WithTimestamp(timestamp) + } + if text != nil { + b = b.WithText(*text) + } + if unmodifiedText != nil { + b = b.WithUnmodifiedText(*unmodifiedText) + } + if keyIdentifier != nil { + b = b.WithKeyIdentifier(*keyIdentifier) + } + if code != nil { + b = b.WithCode(*code) + } + if key != nil { + b = b.WithKey(*key) + } + if windowsVirtualKeyCode != nil { + b = b.WithWindowsVirtualKeyCode(*windowsVirtualKeyCode) + } + if nativeVirtualKeyCode != nil { + b = b.WithNativeVirtualKeyCode(*nativeVirtualKeyCode) + } + if autoRepeat != nil { + b = b.WithAutoRepeat(*autoRepeat) + } + if isKeypad != nil { + b = b.WithIsKeypad(*isKeypad) + } + if isSystemKey != nil { + b = b.WithIsSystemKey(*isSystemKey) + } + if location != nil { + b = b.WithLocation(*location) + } + return b.Do(doInput.ctxWithExecutor) +} + +// InsertText this method emulates inserting text that doesn't come from a +// key press, for example an emoji keyboard or an IME. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-insertText +// +// parameters: +// - `text`: The text to insert. +func (doInput Input) InsertText(text string) (err error) { + b := input.InsertText(text) + return b.Do(doInput.ctxWithExecutor) +} + +// DispatchMouseEvent dispatches a mouse event to the page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchMouseEvent +// +// parameters: +// - `type`: Type of the mouse event. +// - `x`: X coordinate of the event relative to the main frame's viewport in CSS pixels. +// - `y`: Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to the top of the viewport and Y increases as it proceeds towards the bottom of the viewport. +// - `modifiers`: This can be nil. (Optional) Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). +// - `timestamp`: This can be nil. (Optional) Time at which the event occurred. +// - `button`: This can be nil. (Optional) Mouse button (default: "none"). +// - `buttons`: This can be nil. (Optional) A number indicating which buttons are pressed on the mouse when a mouse event is triggered. Left=1, Right=2, Middle=4, Back=8, Forward=16, None=0. +// - `clickCount`: This can be nil. (Optional) Number of times the mouse button was clicked (default: 0). +// - `deltaX`: This can be nil. (Optional) X delta in CSS pixels for mouse wheel event (default: 0). +// - `deltaY`: This can be nil. (Optional) Y delta in CSS pixels for mouse wheel event (default: 0). +// - `pointerType`: This can be nil. (Optional) Pointer type (default: "mouse"). +func (doInput Input) DispatchMouseEvent(typeVal input.MouseType, x float64, y float64, modifiers *input.Modifier, timestamp *input.TimeSinceEpoch, button *input.ButtonType, buttons *int64, clickCount *int64, deltaX *float64, deltaY *float64, pointerType *input.DispatchMouseEventPointerType) (err error) { + b := input.DispatchMouseEvent(typeVal, x, y) + if modifiers != nil { + b = b.WithModifiers(*modifiers) + } + if timestamp != nil { + b = b.WithTimestamp(timestamp) + } + if button != nil { + b = b.WithButton(*button) + } + if buttons != nil { + b = b.WithButtons(*buttons) + } + if clickCount != nil { + b = b.WithClickCount(*clickCount) + } + if deltaX != nil { + b = b.WithDeltaX(*deltaX) + } + if deltaY != nil { + b = b.WithDeltaY(*deltaY) + } + if pointerType != nil { + b = b.WithPointerType(*pointerType) + } + return b.Do(doInput.ctxWithExecutor) +} + +// DispatchTouchEvent dispatches a touch event to the page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-dispatchTouchEvent +// +// parameters: +// - `type`: Type of the touch event. TouchEnd and TouchCancel must not contain any touch points, while TouchStart and TouchMove must contains at least one. +// - `touchPoints`: Active touch points on the touch device. One event per any changed point (compared to previous touch event in a sequence) is generated, emulating pressing/moving/releasing points one by one. +// - `modifiers`: This can be nil. (Optional) Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). +// - `timestamp`: This can be nil. (Optional) Time at which the event occurred. +func (doInput Input) DispatchTouchEvent(typeVal input.TouchType, touchPoints []*input.TouchPoint, modifiers *input.Modifier, timestamp *input.TimeSinceEpoch) (err error) { + b := input.DispatchTouchEvent(typeVal, touchPoints) + if modifiers != nil { + b = b.WithModifiers(*modifiers) + } + if timestamp != nil { + b = b.WithTimestamp(timestamp) + } + return b.Do(doInput.ctxWithExecutor) +} + +// EmulateTouchFromMouseEvent emulates touch event from the mouse event +// parameters. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-emulateTouchFromMouseEvent +// +// parameters: +// - `type`: Type of the mouse event. +// - `x`: X coordinate of the mouse pointer in DIP. +// - `y`: Y coordinate of the mouse pointer in DIP. +// - `button`: Mouse button. +// - `timestamp`: This can be nil. (Optional) Time at which the event occurred (default: current time). +// - `deltaX`: This can be nil. (Optional) X delta in DIP for mouse wheel event (default: 0). +// - `deltaY`: This can be nil. (Optional) Y delta in DIP for mouse wheel event (default: 0). +// - `modifiers`: This can be nil. (Optional) Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 (default: 0). +// - `clickCount`: This can be nil. (Optional) Number of times the mouse button was clicked (default: 0). +func (doInput Input) EmulateTouchFromMouseEvent(typeVal input.MouseType, x int64, y int64, button input.ButtonType, timestamp *input.TimeSinceEpoch, deltaX *float64, deltaY *float64, modifiers *input.Modifier, clickCount *int64) (err error) { + b := input.EmulateTouchFromMouseEvent(typeVal, x, y, button) + if timestamp != nil { + b = b.WithTimestamp(timestamp) + } + if deltaX != nil { + b = b.WithDeltaX(*deltaX) + } + if deltaY != nil { + b = b.WithDeltaY(*deltaY) + } + if modifiers != nil { + b = b.WithModifiers(*modifiers) + } + if clickCount != nil { + b = b.WithClickCount(*clickCount) + } + return b.Do(doInput.ctxWithExecutor) +} + +// SetIgnoreInputEvents ignores input events (useful while auditing page). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-setIgnoreInputEvents +// +// parameters: +// - `ignore`: Ignores input events processing when set to true. +func (doInput Input) SetIgnoreInputEvents(ignore bool) (err error) { + b := input.SetIgnoreInputEvents(ignore) + return b.Do(doInput.ctxWithExecutor) +} + +// SynthesizePinchGesture synthesizes a pinch gesture over a time period by +// issuing appropriate touch events. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-synthesizePinchGesture +// +// parameters: +// - `x`: X coordinate of the start of the gesture in CSS pixels. +// - `y`: Y coordinate of the start of the gesture in CSS pixels. +// - `scaleFactor`: Relative scale factor after zooming (>1.0 zooms in, <1.0 zooms out). +// - `relativeSpeed`: This can be nil. (Optional) Relative pointer speed in pixels per second (default: 800). +// - `gestureSourceType`: This can be nil. (Optional) Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type). +func (doInput Input) SynthesizePinchGesture(x float64, y float64, scaleFactor float64, relativeSpeed *int64, gestureSourceType *input.GestureType) (err error) { + b := input.SynthesizePinchGesture(x, y, scaleFactor) + if relativeSpeed != nil { + b = b.WithRelativeSpeed(*relativeSpeed) + } + if gestureSourceType != nil { + b = b.WithGestureSourceType(*gestureSourceType) + } + return b.Do(doInput.ctxWithExecutor) +} + +// SynthesizeScrollGesture synthesizes a scroll gesture over a time period by +// issuing appropriate touch events. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-synthesizeScrollGesture +// +// parameters: +// - `x`: X coordinate of the start of the gesture in CSS pixels. +// - `y`: Y coordinate of the start of the gesture in CSS pixels. +// - `xDistance`: This can be nil. (Optional) The distance to scroll along the X axis (positive to scroll left). +// - `yDistance`: This can be nil. (Optional) The distance to scroll along the Y axis (positive to scroll up). +// - `xOverscroll`: This can be nil. (Optional) The number of additional pixels to scroll back along the X axis, in addition to the given distance. +// - `yOverscroll`: This can be nil. (Optional) The number of additional pixels to scroll back along the Y axis, in addition to the given distance. +// - `preventFling`: This can be nil. (Optional) Prevent fling (default: true). +// - `speed`: This can be nil. (Optional) Swipe speed in pixels per second (default: 800). +// - `gestureSourceType`: This can be nil. (Optional) Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type). +// - `repeatCount`: This can be nil. (Optional) The number of times to repeat the gesture (default: 0). +// - `repeatDelayMs`: This can be nil. (Optional) The number of milliseconds delay between each repeat. (default: 250). +// - `interactionMarkerName`: This can be nil. (Optional) The name of the interaction markers to generate, if not empty (default: ""). +func (doInput Input) SynthesizeScrollGesture(x float64, y float64, xDistance *float64, yDistance *float64, xOverscroll *float64, yOverscroll *float64, preventFling *bool, speed *int64, gestureSourceType *input.GestureType, repeatCount *int64, repeatDelayMs *int64, interactionMarkerName *string) (err error) { + b := input.SynthesizeScrollGesture(x, y) + if xDistance != nil { + b = b.WithXDistance(*xDistance) + } + if yDistance != nil { + b = b.WithYDistance(*yDistance) + } + if xOverscroll != nil { + b = b.WithXOverscroll(*xOverscroll) + } + if yOverscroll != nil { + b = b.WithYOverscroll(*yOverscroll) + } + if preventFling != nil { + b = b.WithPreventFling(*preventFling) + } + if speed != nil { + b = b.WithSpeed(*speed) + } + if gestureSourceType != nil { + b = b.WithGestureSourceType(*gestureSourceType) + } + if repeatCount != nil { + b = b.WithRepeatCount(*repeatCount) + } + if repeatDelayMs != nil { + b = b.WithRepeatDelayMs(*repeatDelayMs) + } + if interactionMarkerName != nil { + b = b.WithInteractionMarkerName(*interactionMarkerName) + } + return b.Do(doInput.ctxWithExecutor) +} + +// SynthesizeTapGesture synthesizes a tap gesture over a time period by +// issuing appropriate touch events. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Input#method-synthesizeTapGesture +// +// parameters: +// - `x`: X coordinate of the start of the gesture in CSS pixels. +// - `y`: Y coordinate of the start of the gesture in CSS pixels. +// - `duration`: This can be nil. (Optional) Duration between touchdown and touchup events in ms (default: 50). +// - `tapCount`: This can be nil. (Optional) Number of times to perform the tap (e.g. 2 for double tap, default: 1). +// - `gestureSourceType`: This can be nil. (Optional) Which type of input events to be generated (default: 'default', which queries the platform for the preferred input type). +func (doInput Input) SynthesizeTapGesture(x float64, y float64, duration *int64, tapCount *int64, gestureSourceType *input.GestureType) (err error) { + b := input.SynthesizeTapGesture(x, y) + if duration != nil { + b = b.WithDuration(*duration) + } + if tapCount != nil { + b = b.WithTapCount(*tapCount) + } + if gestureSourceType != nil { + b = b.WithGestureSourceType(*gestureSourceType) + } + return b.Do(doInput.ctxWithExecutor) +} diff --git a/domain/inspector.go b/domain/inspector.go new file mode 100644 index 0000000..815f386 --- /dev/null +++ b/domain/inspector.go @@ -0,0 +1,30 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/inspector" +) + +// Inspector executes a cdproto command under Inspector domain. +type Inspector struct { + ctxWithExecutor context.Context +} + +// Disable disables inspector domain notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Inspector#method-disable +func (doInspector Inspector) Disable() (err error) { + b := inspector.Disable() + return b.Do(doInspector.ctxWithExecutor) +} + +// Enable enables inspector domain notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Inspector#method-enable +func (doInspector Inspector) Enable() (err error) { + b := inspector.Enable() + return b.Do(doInspector.ctxWithExecutor) +} diff --git a/domain/io.go b/domain/io.go new file mode 100644 index 0000000..57940cf --- /dev/null +++ b/domain/io.go @@ -0,0 +1,63 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/io" + "github.com/chromedp/cdproto/runtime" +) + +// IO executes a cdproto command under IO domain. +type IO struct { + ctxWithExecutor context.Context +} + +// Close close the stream, discard any temporary backing storage. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IO#method-close +// +// parameters: +// - `handle`: Handle of the stream to close. +func (doIO IO) Close(handle io.StreamHandle) (err error) { + b := io.Close(handle) + return b.Do(doIO.ctxWithExecutor) +} + +// Read read a chunk of the stream. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IO#method-read +// +// parameters: +// - `handle`: Handle of the stream to read. +// - `offset`: This can be nil. (Optional) Seek to the specified offset before reading (if not specificed, proceed with offset following the last read). Some types of streams may only support sequential reads. +// - `size`: This can be nil. (Optional) Maximum number of bytes to read (left upon the agent discretion if not specified). +// +// returns: +// - `retData`: Data that were read. +// - `retEOF`: Set if the end-of-file condition occurred while reading. +func (doIO IO) Read(handle io.StreamHandle, offset *int64, size *int64) (retData string, retEOF bool, err error) { + b := io.Read(handle) + if offset != nil { + b = b.WithOffset(*offset) + } + if size != nil { + b = b.WithSize(*size) + } + return b.Do(doIO.ctxWithExecutor) +} + +// ResolveBlob return UUID of Blob object specified by a remote object id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/IO#method-resolveBlob +// +// parameters: +// - `objectID`: Object id of a Blob object wrapper. +// +// returns: +// - `retUUID`: UUID of the specified Blob. +func (doIO IO) ResolveBlob(objectID runtime.RemoteObjectID) (retUUID string, err error) { + b := io.ResolveBlob(objectID) + return b.Do(doIO.ctxWithExecutor) +} diff --git a/domain/layertree.go b/domain/layertree.go new file mode 100644 index 0000000..b0c2d67 --- /dev/null +++ b/domain/layertree.go @@ -0,0 +1,153 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/dom" + "github.com/chromedp/cdproto/layertree" + "github.com/mailru/easyjson" +) + +// LayerTree executes a cdproto command under LayerTree domain. +type LayerTree struct { + ctxWithExecutor context.Context +} + +// CompositingReasons provides the reasons why the given layer was +// composited. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-compositingReasons +// +// parameters: +// - `layerID`: The id of the layer for which we want to get the reasons it was composited. +// +// returns: +// - `retCompositingReasons`: A list of strings specifying reasons for the given layer to become composited. +func (doLayerTree LayerTree) CompositingReasons(layerID layertree.LayerID) (retCompositingReasons []string, err error) { + b := layertree.CompositingReasons(layerID) + return b.Do(doLayerTree.ctxWithExecutor) +} + +// Disable disables compositing tree inspection. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-disable +func (doLayerTree LayerTree) Disable() (err error) { + b := layertree.Disable() + return b.Do(doLayerTree.ctxWithExecutor) +} + +// Enable enables compositing tree inspection. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-enable +func (doLayerTree LayerTree) Enable() (err error) { + b := layertree.Enable() + return b.Do(doLayerTree.ctxWithExecutor) +} + +// LoadSnapshot returns the snapshot identifier. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-loadSnapshot +// +// parameters: +// - `tiles`: An array of tiles composing the snapshot. +// +// returns: +// - `retSnapshotID`: The id of the snapshot. +func (doLayerTree LayerTree) LoadSnapshot(tiles []*layertree.PictureTile) (retSnapshotID layertree.SnapshotID, err error) { + b := layertree.LoadSnapshot(tiles) + return b.Do(doLayerTree.ctxWithExecutor) +} + +// MakeSnapshot returns the layer snapshot identifier. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-makeSnapshot +// +// parameters: +// - `layerID`: The id of the layer. +// +// returns: +// - `retSnapshotID`: The id of the layer snapshot. +func (doLayerTree LayerTree) MakeSnapshot(layerID layertree.LayerID) (retSnapshotID layertree.SnapshotID, err error) { + b := layertree.MakeSnapshot(layerID) + return b.Do(doLayerTree.ctxWithExecutor) +} + +// ProfileSnapshot [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-profileSnapshot +// +// parameters: +// - `snapshotID`: The id of the layer snapshot. +// - `minRepeatCount`: This can be nil. (Optional) The maximum number of times to replay the snapshot (1, if not specified). +// - `minDuration`: This can be nil. (Optional) The minimum duration (in seconds) to replay the snapshot. +// - `clipRect`: This can be nil. (Optional) The clip rectangle to apply when replaying the snapshot. +// +// returns: +// - `retTimings`: The array of paint profiles, one per run. +func (doLayerTree LayerTree) ProfileSnapshot(snapshotID layertree.SnapshotID, minRepeatCount *int64, minDuration *float64, clipRect *dom.Rect) (retTimings []layertree.PaintProfile, err error) { + b := layertree.ProfileSnapshot(snapshotID) + if minRepeatCount != nil { + b = b.WithMinRepeatCount(*minRepeatCount) + } + if minDuration != nil { + b = b.WithMinDuration(*minDuration) + } + if clipRect != nil { + b = b.WithClipRect(clipRect) + } + return b.Do(doLayerTree.ctxWithExecutor) +} + +// ReleaseSnapshot releases layer snapshot captured by the back-end. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-releaseSnapshot +// +// parameters: +// - `snapshotID`: The id of the layer snapshot. +func (doLayerTree LayerTree) ReleaseSnapshot(snapshotID layertree.SnapshotID) (err error) { + b := layertree.ReleaseSnapshot(snapshotID) + return b.Do(doLayerTree.ctxWithExecutor) +} + +// ReplaySnapshot replays the layer snapshot and returns the resulting +// bitmap. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-replaySnapshot +// +// parameters: +// - `snapshotID`: The id of the layer snapshot. +// - `fromStep`: This can be nil. (Optional) The first step to replay from (replay from the very start if not specified). +// - `toStep`: This can be nil. (Optional) The last step to replay to (replay till the end if not specified). +// - `scale`: This can be nil. (Optional) The scale to apply while replaying (defaults to 1). +// +// returns: +// - `retDataURL`: A data: URL for resulting image. +func (doLayerTree LayerTree) ReplaySnapshot(snapshotID layertree.SnapshotID, fromStep *int64, toStep *int64, scale *float64) (retDataURL string, err error) { + b := layertree.ReplaySnapshot(snapshotID) + if fromStep != nil { + b = b.WithFromStep(*fromStep) + } + if toStep != nil { + b = b.WithToStep(*toStep) + } + if scale != nil { + b = b.WithScale(*scale) + } + return b.Do(doLayerTree.ctxWithExecutor) +} + +// SnapshotCommandLog replays the layer snapshot and returns canvas log. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/LayerTree#method-snapshotCommandLog +// +// parameters: +// - `snapshotID`: The id of the layer snapshot. +// +// returns: +// - `retCommandLog`: The array of canvas function calls. +func (doLayerTree LayerTree) SnapshotCommandLog(snapshotID layertree.SnapshotID) (retCommandLog []easyjson.RawMessage, err error) { + b := layertree.SnapshotCommandLog(snapshotID) + return b.Do(doLayerTree.ctxWithExecutor) +} diff --git a/domain/log.go b/domain/log.go new file mode 100644 index 0000000..31b3e14 --- /dev/null +++ b/domain/log.go @@ -0,0 +1,59 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/log" +) + +// Log executes a cdproto command under Log domain. +type Log struct { + ctxWithExecutor context.Context +} + +// Clear clears the log. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Log#method-clear +func (doLog Log) Clear() (err error) { + b := log.Clear() + return b.Do(doLog.ctxWithExecutor) +} + +// Disable disables log domain, prevents further log entries from being +// reported to the client. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Log#method-disable +func (doLog Log) Disable() (err error) { + b := log.Disable() + return b.Do(doLog.ctxWithExecutor) +} + +// Enable enables log domain, sends the entries collected so far to the +// client by means of the entryAdded notification. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Log#method-enable +func (doLog Log) Enable() (err error) { + b := log.Enable() + return b.Do(doLog.ctxWithExecutor) +} + +// StartViolationsReport start violation reporting. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Log#method-startViolationsReport +// +// parameters: +// - `config`: Configuration for violations. +func (doLog Log) StartViolationsReport(config []*log.ViolationSetting) (err error) { + b := log.StartViolationsReport(config) + return b.Do(doLog.ctxWithExecutor) +} + +// StopViolationsReport stop violation reporting. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Log#method-stopViolationsReport +func (doLog Log) StopViolationsReport() (err error) { + b := log.StopViolationsReport() + return b.Do(doLog.ctxWithExecutor) +} diff --git a/domain/media.go b/domain/media.go new file mode 100644 index 0000000..906027f --- /dev/null +++ b/domain/media.go @@ -0,0 +1,30 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/media" +) + +// Media executes a cdproto command under Media domain. +type Media struct { + ctxWithExecutor context.Context +} + +// Enable enables the Media domain. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Media#method-enable +func (doMedia Media) Enable() (err error) { + b := media.Enable() + return b.Do(doMedia.ctxWithExecutor) +} + +// Disable disables the Media domain. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Media#method-disable +func (doMedia Media) Disable() (err error) { + b := media.Disable() + return b.Do(doMedia.ctxWithExecutor) +} diff --git a/domain/memory.go b/domain/memory.go new file mode 100644 index 0000000..0d69798 --- /dev/null +++ b/domain/memory.go @@ -0,0 +1,130 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/memory" +) + +// Memory executes a cdproto command under Memory domain. +type Memory struct { + ctxWithExecutor context.Context +} + +// GetDOMCounters [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-getDOMCounters +// +// returns: +// - `retDocuments` +// - `retNodes` +// - `retJsEventListeners` +func (doMemory Memory) GetDOMCounters() (retDocuments int64, retNodes int64, retJsEventListeners int64, err error) { + b := memory.GetDOMCounters() + return b.Do(doMemory.ctxWithExecutor) +} + +// PrepareForLeakDetection [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-prepareForLeakDetection +func (doMemory Memory) PrepareForLeakDetection() (err error) { + b := memory.PrepareForLeakDetection() + return b.Do(doMemory.ctxWithExecutor) +} + +// ForciblyPurgeJavaScriptMemory simulate OomIntervention by purging V8 +// memory. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-forciblyPurgeJavaScriptMemory +func (doMemory Memory) ForciblyPurgeJavaScriptMemory() (err error) { + b := memory.ForciblyPurgeJavaScriptMemory() + return b.Do(doMemory.ctxWithExecutor) +} + +// SetPressureNotificationsSuppressed enable/disable suppressing memory +// pressure notifications in all processes. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-setPressureNotificationsSuppressed +// +// parameters: +// - `suppressed`: If true, memory pressure notifications will be suppressed. +func (doMemory Memory) SetPressureNotificationsSuppressed(suppressed bool) (err error) { + b := memory.SetPressureNotificationsSuppressed(suppressed) + return b.Do(doMemory.ctxWithExecutor) +} + +// SimulatePressureNotification simulate a memory pressure notification in +// all processes. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-simulatePressureNotification +// +// parameters: +// - `level`: Memory pressure level of the notification. +func (doMemory Memory) SimulatePressureNotification(level memory.PressureLevel) (err error) { + b := memory.SimulatePressureNotification(level) + return b.Do(doMemory.ctxWithExecutor) +} + +// StartSampling start collecting native memory profile. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-startSampling +// +// parameters: +// - `samplingInterval`: This can be nil. (Optional) Average number of bytes between samples. +// - `suppressRandomness`: This can be nil. (Optional) Do not randomize intervals between samples. +func (doMemory Memory) StartSampling(samplingInterval *int64, suppressRandomness *bool) (err error) { + b := memory.StartSampling() + if samplingInterval != nil { + b = b.WithSamplingInterval(*samplingInterval) + } + if suppressRandomness != nil { + b = b.WithSuppressRandomness(*suppressRandomness) + } + return b.Do(doMemory.ctxWithExecutor) +} + +// StopSampling stop collecting native memory profile. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-stopSampling +func (doMemory Memory) StopSampling() (err error) { + b := memory.StopSampling() + return b.Do(doMemory.ctxWithExecutor) +} + +// GetAllTimeSamplingProfile retrieve native memory allocations profile +// collected since renderer process startup. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-getAllTimeSamplingProfile +// +// returns: +// - `retProfile` +func (doMemory Memory) GetAllTimeSamplingProfile() (retProfile *memory.SamplingProfile, err error) { + b := memory.GetAllTimeSamplingProfile() + return b.Do(doMemory.ctxWithExecutor) +} + +// GetBrowserSamplingProfile retrieve native memory allocations profile +// collected since browser process startup. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-getBrowserSamplingProfile +// +// returns: +// - `retProfile` +func (doMemory Memory) GetBrowserSamplingProfile() (retProfile *memory.SamplingProfile, err error) { + b := memory.GetBrowserSamplingProfile() + return b.Do(doMemory.ctxWithExecutor) +} + +// GetSamplingProfile retrieve native memory allocations profile collected +// since last startSampling call. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Memory#method-getSamplingProfile +// +// returns: +// - `retProfile` +func (doMemory Memory) GetSamplingProfile() (retProfile *memory.SamplingProfile, err error) { + b := memory.GetSamplingProfile() + return b.Do(doMemory.ctxWithExecutor) +} diff --git a/domain/network.go b/domain/network.go new file mode 100644 index 0000000..7f468a5 --- /dev/null +++ b/domain/network.go @@ -0,0 +1,365 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/debugger" + "github.com/chromedp/cdproto/io" + "github.com/chromedp/cdproto/network" +) + +// Network executes a cdproto command under Network domain. +type Network struct { + ctxWithExecutor context.Context +} + +// ClearBrowserCache clears browser cache. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-clearBrowserCache +func (doNetwork Network) ClearBrowserCache() (err error) { + b := network.ClearBrowserCache() + return b.Do(doNetwork.ctxWithExecutor) +} + +// ClearBrowserCookies clears browser cookies. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-clearBrowserCookies +func (doNetwork Network) ClearBrowserCookies() (err error) { + b := network.ClearBrowserCookies() + return b.Do(doNetwork.ctxWithExecutor) +} + +// DeleteCookies deletes browser cookies with matching name and url or +// domain/path pair. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-deleteCookies +// +// parameters: +// - `name`: Name of the cookies to remove. +// - `url`: This can be nil. (Optional) If specified, deletes all the cookies with the given name where domain and path match provided URL. +// - `domain`: This can be nil. (Optional) If specified, deletes only cookies with the exact domain. +// - `path`: This can be nil. (Optional) If specified, deletes only cookies with the exact path. +func (doNetwork Network) DeleteCookies(name string, url *string, domain *string, path *string) (err error) { + b := network.DeleteCookies(name) + if url != nil { + b = b.WithURL(*url) + } + if domain != nil { + b = b.WithDomain(*domain) + } + if path != nil { + b = b.WithPath(*path) + } + return b.Do(doNetwork.ctxWithExecutor) +} + +// Disable disables network tracking, prevents network events from being sent +// to the client. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-disable +func (doNetwork Network) Disable() (err error) { + b := network.Disable() + return b.Do(doNetwork.ctxWithExecutor) +} + +// EmulateNetworkConditions activates emulation of network conditions. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-emulateNetworkConditions +// +// parameters: +// - `offline`: True to emulate internet disconnection. +// - `latency`: Minimum latency from request sent to response headers received (ms). +// - `downloadThroughput`: Maximal aggregated download throughput (bytes/sec). -1 disables download throttling. +// - `uploadThroughput`: Maximal aggregated upload throughput (bytes/sec). -1 disables upload throttling. +// - `connectionType`: This can be nil. (Optional) Connection type if known. +func (doNetwork Network) EmulateNetworkConditions(offline bool, latency float64, downloadThroughput float64, uploadThroughput float64, connectionType *network.ConnectionType) (err error) { + b := network.EmulateNetworkConditions(offline, latency, downloadThroughput, uploadThroughput) + if connectionType != nil { + b = b.WithConnectionType(*connectionType) + } + return b.Do(doNetwork.ctxWithExecutor) +} + +// Enable enables network tracking, network events will now be delivered to +// the client. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-enable +// +// parameters: +// - `maxTotalBufferSize`: This can be nil. (Optional) Buffer size in bytes to use when preserving network payloads (XHRs, etc). +// - `maxResourceBufferSize`: This can be nil. (Optional) Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc). +// - `maxPostDataSize`: This can be nil. (Optional) Longest post body size (in bytes) that would be included in requestWillBeSent notification +func (doNetwork Network) Enable(maxTotalBufferSize *int64, maxResourceBufferSize *int64, maxPostDataSize *int64) (err error) { + b := network.Enable() + if maxTotalBufferSize != nil { + b = b.WithMaxTotalBufferSize(*maxTotalBufferSize) + } + if maxResourceBufferSize != nil { + b = b.WithMaxResourceBufferSize(*maxResourceBufferSize) + } + if maxPostDataSize != nil { + b = b.WithMaxPostDataSize(*maxPostDataSize) + } + return b.Do(doNetwork.ctxWithExecutor) +} + +// GetAllCookies returns all browser cookies. Depending on the backend +// support, will return detailed cookie information in the cookies field. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getAllCookies +// +// returns: +// - `retCookies`: Array of cookie objects. +func (doNetwork Network) GetAllCookies() (retCookies []*network.Cookie, err error) { + b := network.GetAllCookies() + return b.Do(doNetwork.ctxWithExecutor) +} + +// GetCertificate returns the DER-encoded certificate. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCertificate +// +// parameters: +// - `origin`: Origin to get certificate for. +// +// returns: +// - `retTableNames` +func (doNetwork Network) GetCertificate(origin string) (retTableNames []string, err error) { + b := network.GetCertificate(origin) + return b.Do(doNetwork.ctxWithExecutor) +} + +// GetCookies returns all browser cookies for the current URL. Depending on +// the backend support, will return detailed cookie information in the cookies +// field. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getCookies +// +// parameters: +// - `urls`: This can be nil. (Optional) The list of URLs for which applicable cookies will be fetched +// +// returns: +// - `retCookies`: Array of cookie objects. +func (doNetwork Network) GetCookies(urls []string) (retCookies []*network.Cookie, err error) { + b := network.GetCookies() + if urls != nil { + b = b.WithUrls(urls) + } + return b.Do(doNetwork.ctxWithExecutor) +} + +// GetResponseBody returns content served for the given request. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBody +// +// parameters: +// - `requestID`: Identifier of the network request to get content for. +// +// returns: +// - `retBody`: Response body. +func (doNetwork Network) GetResponseBody(requestID network.RequestID) (retBody []byte, err error) { + b := network.GetResponseBody(requestID) + return b.Do(doNetwork.ctxWithExecutor) +} + +// GetRequestPostData returns post data sent with the request. Returns an +// error when no data was sent with the request. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getRequestPostData +// +// parameters: +// - `requestID`: Identifier of the network request to get content for. +// +// returns: +// - `retPostData`: Request body string, omitting files from multipart requests +func (doNetwork Network) GetRequestPostData(requestID network.RequestID) (retPostData string, err error) { + b := network.GetRequestPostData(requestID) + return b.Do(doNetwork.ctxWithExecutor) +} + +// GetResponseBodyForInterception returns content served for the given +// currently intercepted request. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-getResponseBodyForInterception +// +// parameters: +// - `interceptionID`: Identifier for the intercepted request to get body for. +// +// returns: +// - `retBody`: Response body. +func (doNetwork Network) GetResponseBodyForInterception(interceptionID network.InterceptionID) (retBody []byte, err error) { + b := network.GetResponseBodyForInterception(interceptionID) + return b.Do(doNetwork.ctxWithExecutor) +} + +// TakeResponseBodyForInterceptionAsStream returns a handle to the stream +// representing the response body. Note that after this command, the intercepted +// request can't be continued as is -- you either need to cancel it or to +// provide the response body. The stream only supports sequential read, IO.read +// will fail if the position is specified. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-takeResponseBodyForInterceptionAsStream +// +// parameters: +// - `interceptionID` +// +// returns: +// - `retStream` +func (doNetwork Network) TakeResponseBodyForInterceptionAsStream(interceptionID network.InterceptionID) (retStream io.StreamHandle, err error) { + b := network.TakeResponseBodyForInterceptionAsStream(interceptionID) + return b.Do(doNetwork.ctxWithExecutor) +} + +// ReplayXHR this method sends a new XMLHttpRequest which is identical to the +// original one. The following parameters should be identical: method, url, +// async, request body, extra headers, withCredentials attribute, user, +// password. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-replayXHR +// +// parameters: +// - `requestID`: Identifier of XHR to replay. +func (doNetwork Network) ReplayXHR(requestID network.RequestID) (err error) { + b := network.ReplayXHR(requestID) + return b.Do(doNetwork.ctxWithExecutor) +} + +// SearchInResponseBody searches for given string in response content. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-searchInResponseBody +// +// parameters: +// - `requestID`: Identifier of the network response to search. +// - `query`: String to search for. +// - `caseSensitive`: This can be nil. (Optional) If true, search is case sensitive. +// - `isRegex`: This can be nil. (Optional) If true, treats string parameter as regex. +// +// returns: +// - `retResult`: List of search matches. +func (doNetwork Network) SearchInResponseBody(requestID network.RequestID, query string, caseSensitive *bool, isRegex *bool) (retResult []*debugger.SearchMatch, err error) { + b := network.SearchInResponseBody(requestID, query) + if caseSensitive != nil { + b = b.WithCaseSensitive(*caseSensitive) + } + if isRegex != nil { + b = b.WithIsRegex(*isRegex) + } + return b.Do(doNetwork.ctxWithExecutor) +} + +// SetBlockedURLS blocks URLs from loading. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBlockedURLs +// +// parameters: +// - `urls`: URL patterns to block. Wildcards ('*') are allowed. +func (doNetwork Network) SetBlockedURLS(urls []string) (err error) { + b := network.SetBlockedURLS(urls) + return b.Do(doNetwork.ctxWithExecutor) +} + +// SetBypassServiceWorker toggles ignoring of service worker for each +// request. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setBypassServiceWorker +// +// parameters: +// - `bypass`: Bypass service worker and load from network. +func (doNetwork Network) SetBypassServiceWorker(bypass bool) (err error) { + b := network.SetBypassServiceWorker(bypass) + return b.Do(doNetwork.ctxWithExecutor) +} + +// SetCacheDisabled toggles ignoring cache for each request. If true, cache +// will not be used. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCacheDisabled +// +// parameters: +// - `cacheDisabled`: Cache disabled state. +func (doNetwork Network) SetCacheDisabled(cacheDisabled bool) (err error) { + b := network.SetCacheDisabled(cacheDisabled) + return b.Do(doNetwork.ctxWithExecutor) +} + +// SetCookie sets a cookie with the given cookie data; may overwrite +// equivalent cookies if they exist. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookie +// +// parameters: +// - `name`: Cookie name. +// - `value`: Cookie value. +// - `url`: This can be nil. (Optional) The request-URI to associate with the setting of the cookie. This value can affect the default domain and path values of the created cookie. +// - `domain`: This can be nil. (Optional) Cookie domain. +// - `path`: This can be nil. (Optional) Cookie path. +// - `secure`: This can be nil. (Optional) True if cookie is secure. +// - `httpOnly`: This can be nil. (Optional) True if cookie is http-only. +// - `sameSite`: This can be nil. (Optional) Cookie SameSite type. +// - `expires`: This can be nil. (Optional) Cookie expiration date, session cookie if not set +// +// returns: +// - `retSuccess`: True if successfully set cookie. +func (doNetwork Network) SetCookie(name string, value string, url *string, domain *string, path *string, secure *bool, httpOnly *bool, sameSite *network.CookieSameSite, expires *cdp.TimeSinceEpoch) (retSuccess bool, err error) { + b := network.SetCookie(name, value) + if url != nil { + b = b.WithURL(*url) + } + if domain != nil { + b = b.WithDomain(*domain) + } + if path != nil { + b = b.WithPath(*path) + } + if secure != nil { + b = b.WithSecure(*secure) + } + if httpOnly != nil { + b = b.WithHTTPOnly(*httpOnly) + } + if sameSite != nil { + b = b.WithSameSite(*sameSite) + } + if expires != nil { + b = b.WithExpires(expires) + } + return b.Do(doNetwork.ctxWithExecutor) +} + +// SetCookies sets given cookies. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setCookies +// +// parameters: +// - `cookies`: Cookies to be set. +func (doNetwork Network) SetCookies(cookies []*network.CookieParam) (err error) { + b := network.SetCookies(cookies) + return b.Do(doNetwork.ctxWithExecutor) +} + +// SetDataSizeLimitsForTest for testing. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setDataSizeLimitsForTest +// +// parameters: +// - `maxTotalSize`: Maximum total buffer size. +// - `maxResourceSize`: Maximum per-resource size. +func (doNetwork Network) SetDataSizeLimitsForTest(maxTotalSize int64, maxResourceSize int64) (err error) { + b := network.SetDataSizeLimitsForTest(maxTotalSize, maxResourceSize) + return b.Do(doNetwork.ctxWithExecutor) +} + +// SetExtraHTTPHeaders specifies whether to always send extra HTTP headers +// with the requests from this page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setExtraHTTPHeaders +// +// parameters: +// - `headers`: Map with extra HTTP headers. +func (doNetwork Network) SetExtraHTTPHeaders(headers network.Headers) (err error) { + b := network.SetExtraHTTPHeaders(headers) + return b.Do(doNetwork.ctxWithExecutor) +} diff --git a/domain/overlay.go b/domain/overlay.go new file mode 100644 index 0000000..202fe9a --- /dev/null +++ b/domain/overlay.go @@ -0,0 +1,277 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/dom" + "github.com/chromedp/cdproto/overlay" + "github.com/chromedp/cdproto/runtime" + "github.com/mailru/easyjson" +) + +// Overlay executes a cdproto command under Overlay domain. +type Overlay struct { + ctxWithExecutor context.Context +} + +// Disable disables domain notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-disable +func (doOverlay Overlay) Disable() (err error) { + b := overlay.Disable() + return b.Do(doOverlay.ctxWithExecutor) +} + +// Enable enables domain notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-enable +func (doOverlay Overlay) Enable() (err error) { + b := overlay.Enable() + return b.Do(doOverlay.ctxWithExecutor) +} + +// GetHighlightObjectForTest for testing. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-getHighlightObjectForTest +// +// parameters: +// - `nodeID`: Id of the node to get highlight object for. +// - `includeDistance`: This can be nil. (Optional) Whether to include distance info. +// - `includeStyle`: This can be nil. (Optional) Whether to include style info. +// +// returns: +// - `retHighlight`: Highlight data for the node. +func (doOverlay Overlay) GetHighlightObjectForTest(nodeID cdp.NodeID, includeDistance *bool, includeStyle *bool) (retHighlight easyjson.RawMessage, err error) { + b := overlay.GetHighlightObjectForTest(nodeID) + if includeDistance != nil { + b = b.WithIncludeDistance(*includeDistance) + } + if includeStyle != nil { + b = b.WithIncludeStyle(*includeStyle) + } + return b.Do(doOverlay.ctxWithExecutor) +} + +// HideHighlight hides any highlight. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-hideHighlight +func (doOverlay Overlay) HideHighlight() (err error) { + b := overlay.HideHighlight() + return b.Do(doOverlay.ctxWithExecutor) +} + +// HighlightFrame highlights owner element of the frame with given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-highlightFrame +// +// parameters: +// - `frameID`: Identifier of the frame to highlight. +// - `contentColor`: This can be nil. (Optional) The content box highlight fill color (default: transparent). +// - `contentOutlineColor`: This can be nil. (Optional) The content box highlight outline color (default: transparent). +func (doOverlay Overlay) HighlightFrame(frameID cdp.FrameID, contentColor *cdp.RGBA, contentOutlineColor *cdp.RGBA) (err error) { + b := overlay.HighlightFrame(frameID) + if contentColor != nil { + b = b.WithContentColor(contentColor) + } + if contentOutlineColor != nil { + b = b.WithContentOutlineColor(contentOutlineColor) + } + return b.Do(doOverlay.ctxWithExecutor) +} + +// HighlightNode highlights DOM node with given id or with the given +// JavaScript object wrapper. Either nodeId or objectId must be specified. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-highlightNode +// +// parameters: +// - `highlightConfig`: A descriptor for the highlight appearance. +// - `nodeID`: This can be nil. (Optional) Identifier of the node to highlight. +// - `backendNodeID`: This can be nil. (Optional) Identifier of the backend node to highlight. +// - `objectID`: This can be nil. (Optional) JavaScript object id of the node to be highlighted. +// - `selector`: This can be nil. (Optional) Selectors to highlight relevant nodes. +func (doOverlay Overlay) HighlightNode(highlightConfig *overlay.HighlightConfig, nodeID *cdp.NodeID, backendNodeID *cdp.BackendNodeID, objectID *runtime.RemoteObjectID, selector *string) (err error) { + b := overlay.HighlightNode(highlightConfig) + if nodeID != nil { + b = b.WithNodeID(*nodeID) + } + if backendNodeID != nil { + b = b.WithBackendNodeID(*backendNodeID) + } + if objectID != nil { + b = b.WithObjectID(*objectID) + } + if selector != nil { + b = b.WithSelector(*selector) + } + return b.Do(doOverlay.ctxWithExecutor) +} + +// HighlightQuad highlights given quad. Coordinates are absolute with respect +// to the main frame viewport. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-highlightQuad +// +// parameters: +// - `quad`: Quad to highlight +// - `color`: This can be nil. (Optional) The highlight fill color (default: transparent). +// - `outlineColor`: This can be nil. (Optional) The highlight outline color (default: transparent). +func (doOverlay Overlay) HighlightQuad(quad dom.Quad, color *cdp.RGBA, outlineColor *cdp.RGBA) (err error) { + b := overlay.HighlightQuad(quad) + if color != nil { + b = b.WithColor(color) + } + if outlineColor != nil { + b = b.WithOutlineColor(outlineColor) + } + return b.Do(doOverlay.ctxWithExecutor) +} + +// HighlightRect highlights given rectangle. Coordinates are absolute with +// respect to the main frame viewport. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-highlightRect +// +// parameters: +// - `x`: X coordinate +// - `y`: Y coordinate +// - `width`: Rectangle width +// - `height`: Rectangle height +// - `color`: This can be nil. (Optional) The highlight fill color (default: transparent). +// - `outlineColor`: This can be nil. (Optional) The highlight outline color (default: transparent). +func (doOverlay Overlay) HighlightRect(x int64, y int64, width int64, height int64, color *cdp.RGBA, outlineColor *cdp.RGBA) (err error) { + b := overlay.HighlightRect(x, y, width, height) + if color != nil { + b = b.WithColor(color) + } + if outlineColor != nil { + b = b.WithOutlineColor(outlineColor) + } + return b.Do(doOverlay.ctxWithExecutor) +} + +// SetInspectMode enters the 'inspect' mode. In this mode, elements that user +// is hovering over are highlighted. Backend then generates +// 'inspectNodeRequested' event upon element selection. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setInspectMode +// +// parameters: +// - `mode`: Set an inspection mode. +// - `highlightConfig`: This can be nil. (Optional) A descriptor for the highlight appearance of hovered-over nodes. May be omitted if enabled == false. +func (doOverlay Overlay) SetInspectMode(mode overlay.InspectMode, highlightConfig *overlay.HighlightConfig) (err error) { + b := overlay.SetInspectMode(mode) + if highlightConfig != nil { + b = b.WithHighlightConfig(highlightConfig) + } + return b.Do(doOverlay.ctxWithExecutor) +} + +// SetShowAdHighlights highlights owner element of all frames detected to be +// ads. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowAdHighlights +// +// parameters: +// - `show`: True for showing ad highlights +func (doOverlay Overlay) SetShowAdHighlights(show bool) (err error) { + b := overlay.SetShowAdHighlights(show) + return b.Do(doOverlay.ctxWithExecutor) +} + +// SetPausedInDebuggerMessage [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setPausedInDebuggerMessage +// +// parameters: +// - `message`: This can be nil. (Optional) The message to display, also triggers resume and step over controls. +func (doOverlay Overlay) SetPausedInDebuggerMessage(message *string) (err error) { + b := overlay.SetPausedInDebuggerMessage() + if message != nil { + b = b.WithMessage(*message) + } + return b.Do(doOverlay.ctxWithExecutor) +} + +// SetShowDebugBorders requests that backend shows debug borders on layers. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowDebugBorders +// +// parameters: +// - `show`: True for showing debug borders +func (doOverlay Overlay) SetShowDebugBorders(show bool) (err error) { + b := overlay.SetShowDebugBorders(show) + return b.Do(doOverlay.ctxWithExecutor) +} + +// SetShowFPSCounter requests that backend shows the FPS counter. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowFPSCounter +// +// parameters: +// - `show`: True for showing the FPS counter +func (doOverlay Overlay) SetShowFPSCounter(show bool) (err error) { + b := overlay.SetShowFPSCounter(show) + return b.Do(doOverlay.ctxWithExecutor) +} + +// SetShowPaintRects requests that backend shows paint rectangles. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowPaintRects +// +// parameters: +// - `result`: True for showing paint rectangles +func (doOverlay Overlay) SetShowPaintRects(result bool) (err error) { + b := overlay.SetShowPaintRects(result) + return b.Do(doOverlay.ctxWithExecutor) +} + +// SetShowLayoutShiftRegions requests that backend shows layout shift +// regions. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowLayoutShiftRegions +// +// parameters: +// - `result`: True for showing layout shift regions +func (doOverlay Overlay) SetShowLayoutShiftRegions(result bool) (err error) { + b := overlay.SetShowLayoutShiftRegions(result) + return b.Do(doOverlay.ctxWithExecutor) +} + +// SetShowScrollBottleneckRects requests that backend shows scroll bottleneck +// rects. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowScrollBottleneckRects +// +// parameters: +// - `show`: True for showing scroll bottleneck rects +func (doOverlay Overlay) SetShowScrollBottleneckRects(show bool) (err error) { + b := overlay.SetShowScrollBottleneckRects(show) + return b.Do(doOverlay.ctxWithExecutor) +} + +// SetShowHitTestBorders requests that backend shows hit-test borders on +// layers. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowHitTestBorders +// +// parameters: +// - `show`: True for showing hit-test borders +func (doOverlay Overlay) SetShowHitTestBorders(show bool) (err error) { + b := overlay.SetShowHitTestBorders(show) + return b.Do(doOverlay.ctxWithExecutor) +} + +// SetShowViewportSizeOnResize paints viewport size upon main frame resize. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Overlay#method-setShowViewportSizeOnResize +// +// parameters: +// - `show`: Whether to paint size or not. +func (doOverlay Overlay) SetShowViewportSizeOnResize(show bool) (err error) { + b := overlay.SetShowViewportSizeOnResize(show) + return b.Do(doOverlay.ctxWithExecutor) +} diff --git a/domain/page.go b/domain/page.go new file mode 100644 index 0000000..46ebd22 --- /dev/null +++ b/domain/page.go @@ -0,0 +1,671 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/cdproto/debugger" + "github.com/chromedp/cdproto/dom" + "github.com/chromedp/cdproto/io" + "github.com/chromedp/cdproto/page" + "github.com/chromedp/cdproto/runtime" +) + +// Page executes a cdproto command under Page domain. +type Page struct { + ctxWithExecutor context.Context +} + +// AddScriptToEvaluateOnNewDocument evaluates given script in every frame +// upon creation (before loading frame's scripts). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-addScriptToEvaluateOnNewDocument +// +// parameters: +// - `source` +// - `worldName`: This can be nil. (Optional) If specified, creates an isolated world with the given name and evaluates given script in it. This world name will be used as the ExecutionContextDescription::name when the corresponding event is emitted. +// +// returns: +// - `retIdentifier`: Identifier of the added script. +func (doPage Page) AddScriptToEvaluateOnNewDocument(source string, worldName *string) (retIdentifier page.ScriptIdentifier, err error) { + b := page.AddScriptToEvaluateOnNewDocument(source) + if worldName != nil { + b = b.WithWorldName(*worldName) + } + return b.Do(doPage.ctxWithExecutor) +} + +// BringToFront brings page to front (activates tab). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-bringToFront +func (doPage Page) BringToFront() (err error) { + b := page.BringToFront() + return b.Do(doPage.ctxWithExecutor) +} + +// CaptureScreenshot capture page screenshot. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-captureScreenshot +// +// parameters: +// - `format`: This can be nil. (Optional) Image compression format (defaults to png). +// - `quality`: This can be nil. (Optional) Compression quality from range [0..100] (jpeg only). +// - `clip`: This can be nil. (Optional) Capture the screenshot of a given region only. +// - `fromSurface`: This can be nil. (Optional) Capture the screenshot from the surface, rather than the view. Defaults to true. +// +// returns: +// - `retData`: Base64-encoded image data. +func (doPage Page) CaptureScreenshot(format *page.CaptureScreenshotFormat, quality *int64, clip *page.Viewport, fromSurface *bool) (retData []byte, err error) { + b := page.CaptureScreenshot() + if format != nil { + b = b.WithFormat(*format) + } + if quality != nil { + b = b.WithQuality(*quality) + } + if clip != nil { + b = b.WithClip(clip) + } + if fromSurface != nil { + b = b.WithFromSurface(*fromSurface) + } + return b.Do(doPage.ctxWithExecutor) +} + +// CaptureSnapshot returns a snapshot of the page as a string. For MHTML +// format, the serialization includes iframes, shadow DOM, external resources, +// and element-inline styles. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-captureSnapshot +// +// parameters: +// - `format`: This can be nil. (Optional) Format (defaults to mhtml). +// +// returns: +// - `retData`: Serialized page data. +func (doPage Page) CaptureSnapshot(format *page.CaptureSnapshotFormat) (retData string, err error) { + b := page.CaptureSnapshot() + if format != nil { + b = b.WithFormat(*format) + } + return b.Do(doPage.ctxWithExecutor) +} + +// CreateIsolatedWorld creates an isolated world for the given frame. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-createIsolatedWorld +// +// parameters: +// - `frameID`: Id of the frame in which the isolated world should be created. +// - `worldName`: This can be nil. (Optional) An optional name which is reported in the Execution Context. +// - `grantUniveralAccess`: This can be nil. (Optional) Whether or not universal access should be granted to the isolated world. This is a powerful option, use with caution. +// +// returns: +// - `retExecutionContextID`: Execution context of the isolated world. +func (doPage Page) CreateIsolatedWorld(frameID cdp.FrameID, worldName *string, grantUniveralAccess *bool) (retExecutionContextID runtime.ExecutionContextID, err error) { + b := page.CreateIsolatedWorld(frameID) + if worldName != nil { + b = b.WithWorldName(*worldName) + } + if grantUniveralAccess != nil { + b = b.WithGrantUniveralAccess(*grantUniveralAccess) + } + return b.Do(doPage.ctxWithExecutor) +} + +// Disable disables page domain notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-disable +func (doPage Page) Disable() (err error) { + b := page.Disable() + return b.Do(doPage.ctxWithExecutor) +} + +// Enable enables page domain notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-enable +func (doPage Page) Enable() (err error) { + b := page.Enable() + return b.Do(doPage.ctxWithExecutor) +} + +// GetAppManifest [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getAppManifest +// +// returns: +// - `retURL`: Manifest location. +// - `retErrors` +// - `retData`: Manifest content. +func (doPage Page) GetAppManifest() (retURL string, retErrors []*page.AppManifestError, retData string, err error) { + b := page.GetAppManifest() + return b.Do(doPage.ctxWithExecutor) +} + +// GetInstallabilityErrors [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getInstallabilityErrors +// +// returns: +// - `retErrors` +func (doPage Page) GetInstallabilityErrors() (retErrors []string, err error) { + b := page.GetInstallabilityErrors() + return b.Do(doPage.ctxWithExecutor) +} + +// GetFrameTree returns present frame tree structure. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getFrameTree +// +// returns: +// - `retFrameTree`: Present frame tree structure. +func (doPage Page) GetFrameTree() (retFrameTree *page.FrameTree, err error) { + b := page.GetFrameTree() + return b.Do(doPage.ctxWithExecutor) +} + +// GetLayoutMetrics returns metrics relating to the layouting of the page, +// such as viewport bounds/scale. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getLayoutMetrics +// +// returns: +// - `retLayoutViewport`: Metrics relating to the layout viewport. +// - `retVisualViewport`: Metrics relating to the visual viewport. +// - `retContentSize`: Size of scrollable area. +func (doPage Page) GetLayoutMetrics() (retLayoutViewport *page.LayoutViewport, retVisualViewport *page.VisualViewport, retContentSize *dom.Rect, err error) { + b := page.GetLayoutMetrics() + return b.Do(doPage.ctxWithExecutor) +} + +// GetNavigationHistory returns navigation history for the current page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getNavigationHistory +// +// returns: +// - `retCurrentIndex`: Index of the current navigation history entry. +// - `retEntries`: Array of navigation history entries. +func (doPage Page) GetNavigationHistory() (retCurrentIndex int64, retEntries []*page.NavigationEntry, err error) { + b := page.GetNavigationHistory() + return b.Do(doPage.ctxWithExecutor) +} + +// ResetNavigationHistory resets navigation history for the current page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-resetNavigationHistory +func (doPage Page) ResetNavigationHistory() (err error) { + b := page.ResetNavigationHistory() + return b.Do(doPage.ctxWithExecutor) +} + +// GetResourceContent returns content of the given resource. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getResourceContent +// +// parameters: +// - `frameID`: Frame id to get resource for. +// - `url`: URL of the resource to get content for. +// +// returns: +// - `retContent`: Resource content. +func (doPage Page) GetResourceContent(frameID cdp.FrameID, url string) (retContent []byte, err error) { + b := page.GetResourceContent(frameID, url) + return b.Do(doPage.ctxWithExecutor) +} + +// GetResourceTree returns present frame / resource tree structure. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-getResourceTree +// +// returns: +// - `retFrameTree`: Present frame / resource tree structure. +func (doPage Page) GetResourceTree() (retFrameTree *page.FrameResourceTree, err error) { + b := page.GetResourceTree() + return b.Do(doPage.ctxWithExecutor) +} + +// HandleJavaScriptDialog accepts or dismisses a JavaScript initiated dialog +// (alert, confirm, prompt, or onbeforeunload). +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-handleJavaScriptDialog +// +// parameters: +// - `accept`: Whether to accept or dismiss the dialog. +// - `promptText`: This can be nil. (Optional) The text to enter into the dialog prompt before accepting. Used only if this is a prompt dialog. +func (doPage Page) HandleJavaScriptDialog(accept bool, promptText *string) (err error) { + b := page.HandleJavaScriptDialog(accept) + if promptText != nil { + b = b.WithPromptText(*promptText) + } + return b.Do(doPage.ctxWithExecutor) +} + +// Navigate navigates current page to the given URL. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-navigate +// +// parameters: +// - `url`: URL to navigate the page to. +// - `referrer`: This can be nil. (Optional) Referrer URL. +// - `transitionType`: This can be nil. (Optional) Intended transition type. +// - `frameID`: This can be nil. (Optional) Frame id to navigate, if not specified navigates the top frame. +// +// returns: +// - `retFrameID`: Frame id that has navigated (or failed to navigate) +// - `retLoaderID`: Loader identifier. +// - `retErrorText`: User friendly error message, present if and only if navigation has failed. +func (doPage Page) Navigate(url string, referrer *string, transitionType *page.TransitionType, frameID *cdp.FrameID) (retFrameID cdp.FrameID, retLoaderID cdp.LoaderID, retErrorText string, err error) { + b := page.Navigate(url) + if referrer != nil { + b = b.WithReferrer(*referrer) + } + if transitionType != nil { + b = b.WithTransitionType(*transitionType) + } + if frameID != nil { + b = b.WithFrameID(*frameID) + } + return b.Do(doPage.ctxWithExecutor) +} + +// NavigateToHistoryEntry navigates current page to the given history entry. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-navigateToHistoryEntry +// +// parameters: +// - `entryID`: Unique id of the entry to navigate to. +func (doPage Page) NavigateToHistoryEntry(entryID int64) (err error) { + b := page.NavigateToHistoryEntry(entryID) + return b.Do(doPage.ctxWithExecutor) +} + +// PrintToPDF print page as PDF. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-printToPDF +// +// parameters: +// - `landscape`: This can be nil. (Optional) Paper orientation. Defaults to false. +// - `displayHeaderFooter`: This can be nil. (Optional) Display header and footer. Defaults to false. +// - `printBackground`: This can be nil. (Optional) Print background graphics. Defaults to false. +// - `scale`: This can be nil. (Optional) Scale of the webpage rendering. Defaults to 1. +// - `paperWidth`: This can be nil. (Optional) Paper width in inches. Defaults to 8.5 inches. +// - `paperHeight`: This can be nil. (Optional) Paper height in inches. Defaults to 11 inches. +// - `marginTop`: This can be nil. (Optional) Top margin in inches. Defaults to 1cm (~0.4 inches). +// - `marginBottom`: This can be nil. (Optional) Bottom margin in inches. Defaults to 1cm (~0.4 inches). +// - `marginLeft`: This can be nil. (Optional) Left margin in inches. Defaults to 1cm (~0.4 inches). +// - `marginRight`: This can be nil. (Optional) Right margin in inches. Defaults to 1cm (~0.4 inches). +// - `pageRanges`: This can be nil. (Optional) Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. +// - `ignoreInvalidPageRanges`: This can be nil. (Optional) Whether to silently ignore invalid but successfully parsed page ranges, such as '3-2'. Defaults to false. +// - `headerTemplate`: This can be nil. (Optional) HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: - date: formatted print date - title: document title - url: document location - pageNumber: current page number - totalPages: total pages in the document For example, would generate span containing the title. +// - `footerTemplate`: This can be nil. (Optional) HTML template for the print footer. Should use the same format as the headerTemplate. +// - `preferCSSPageSize`: This can be nil. (Optional) Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. +// - `transferMode`: This can be nil. (Optional) return as stream +// +// returns: +// - `retData`: Base64-encoded pdf data. Empty if |returnAsStream| is specified. +// - `retStream`: A handle of the stream that holds resulting PDF data. +func (doPage Page) PrintToPDF(landscape *bool, displayHeaderFooter *bool, printBackground *bool, scale *float64, paperWidth *float64, paperHeight *float64, marginTop *float64, marginBottom *float64, marginLeft *float64, marginRight *float64, pageRanges *string, ignoreInvalidPageRanges *bool, headerTemplate *string, footerTemplate *string, preferCSSPageSize *bool, transferMode *page.PrintToPDFTransferMode) (retData []byte, retStream io.StreamHandle, err error) { + b := page.PrintToPDF() + if landscape != nil { + b = b.WithLandscape(*landscape) + } + if displayHeaderFooter != nil { + b = b.WithDisplayHeaderFooter(*displayHeaderFooter) + } + if printBackground != nil { + b = b.WithPrintBackground(*printBackground) + } + if scale != nil { + b = b.WithScale(*scale) + } + if paperWidth != nil { + b = b.WithPaperWidth(*paperWidth) + } + if paperHeight != nil { + b = b.WithPaperHeight(*paperHeight) + } + if marginTop != nil { + b = b.WithMarginTop(*marginTop) + } + if marginBottom != nil { + b = b.WithMarginBottom(*marginBottom) + } + if marginLeft != nil { + b = b.WithMarginLeft(*marginLeft) + } + if marginRight != nil { + b = b.WithMarginRight(*marginRight) + } + if pageRanges != nil { + b = b.WithPageRanges(*pageRanges) + } + if ignoreInvalidPageRanges != nil { + b = b.WithIgnoreInvalidPageRanges(*ignoreInvalidPageRanges) + } + if headerTemplate != nil { + b = b.WithHeaderTemplate(*headerTemplate) + } + if footerTemplate != nil { + b = b.WithFooterTemplate(*footerTemplate) + } + if preferCSSPageSize != nil { + b = b.WithPreferCSSPageSize(*preferCSSPageSize) + } + if transferMode != nil { + b = b.WithTransferMode(*transferMode) + } + return b.Do(doPage.ctxWithExecutor) +} + +// Reload reloads given page optionally ignoring the cache. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-reload +// +// parameters: +// - `ignoreCache`: This can be nil. (Optional) If true, browser cache is ignored (as if the user pressed Shift+refresh). +// - `scriptToEvaluateOnLoad`: This can be nil. (Optional) If set, the script will be injected into all frames of the inspected page after reload. Argument will be ignored if reloading dataURL origin. +func (doPage Page) Reload(ignoreCache *bool, scriptToEvaluateOnLoad *string) (err error) { + b := page.Reload() + if ignoreCache != nil { + b = b.WithIgnoreCache(*ignoreCache) + } + if scriptToEvaluateOnLoad != nil { + b = b.WithScriptToEvaluateOnLoad(*scriptToEvaluateOnLoad) + } + return b.Do(doPage.ctxWithExecutor) +} + +// RemoveScriptToEvaluateOnNewDocument removes given script from the list. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-removeScriptToEvaluateOnNewDocument +// +// parameters: +// - `identifier` +func (doPage Page) RemoveScriptToEvaluateOnNewDocument(identifier page.ScriptIdentifier) (err error) { + b := page.RemoveScriptToEvaluateOnNewDocument(identifier) + return b.Do(doPage.ctxWithExecutor) +} + +// ScreencastFrameAck acknowledges that a screencast frame has been received +// by the frontend. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-screencastFrameAck +// +// parameters: +// - `sessionID`: Frame number. +func (doPage Page) ScreencastFrameAck(sessionID int64) (err error) { + b := page.ScreencastFrameAck(sessionID) + return b.Do(doPage.ctxWithExecutor) +} + +// SearchInResource searches for given string in resource content. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-searchInResource +// +// parameters: +// - `frameID`: Frame id for resource to search in. +// - `url`: URL of the resource to search in. +// - `query`: String to search for. +// - `caseSensitive`: This can be nil. (Optional) If true, search is case sensitive. +// - `isRegex`: This can be nil. (Optional) If true, treats string parameter as regex. +// +// returns: +// - `retResult`: List of search matches. +func (doPage Page) SearchInResource(frameID cdp.FrameID, url string, query string, caseSensitive *bool, isRegex *bool) (retResult []*debugger.SearchMatch, err error) { + b := page.SearchInResource(frameID, url, query) + if caseSensitive != nil { + b = b.WithCaseSensitive(*caseSensitive) + } + if isRegex != nil { + b = b.WithIsRegex(*isRegex) + } + return b.Do(doPage.ctxWithExecutor) +} + +// SetAdBlockingEnabled enable Chrome's experimental ad filter on all sites. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setAdBlockingEnabled +// +// parameters: +// - `enabled`: Whether to block ads. +func (doPage Page) SetAdBlockingEnabled(enabled bool) (err error) { + b := page.SetAdBlockingEnabled(enabled) + return b.Do(doPage.ctxWithExecutor) +} + +// SetBypassCSP enable page Content Security Policy by-passing. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setBypassCSP +// +// parameters: +// - `enabled`: Whether to bypass page CSP. +func (doPage Page) SetBypassCSP(enabled bool) (err error) { + b := page.SetBypassCSP(enabled) + return b.Do(doPage.ctxWithExecutor) +} + +// SetFontFamilies set generic font families. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setFontFamilies +// +// parameters: +// - `fontFamilies`: Specifies font families to set. If a font family is not specified, it won't be changed. +func (doPage Page) SetFontFamilies(fontFamilies *page.FontFamilies) (err error) { + b := page.SetFontFamilies(fontFamilies) + return b.Do(doPage.ctxWithExecutor) +} + +// SetFontSizes set default font sizes. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setFontSizes +// +// parameters: +// - `fontSizes`: Specifies font sizes to set. If a font size is not specified, it won't be changed. +func (doPage Page) SetFontSizes(fontSizes *page.FontSizes) (err error) { + b := page.SetFontSizes(fontSizes) + return b.Do(doPage.ctxWithExecutor) +} + +// SetDocumentContent sets given markup as the document's HTML. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setDocumentContent +// +// parameters: +// - `frameID`: Frame id to set HTML for. +// - `html`: HTML content to set. +func (doPage Page) SetDocumentContent(frameID cdp.FrameID, html string) (err error) { + b := page.SetDocumentContent(frameID, html) + return b.Do(doPage.ctxWithExecutor) +} + +// SetDownloadBehavior set the behavior when downloading a file. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setDownloadBehavior +// +// parameters: +// - `behavior`: Whether to allow all or deny all download requests, or use default Chrome behavior if available (otherwise deny). +// - `downloadPath`: This can be nil. (Optional) The default path to save downloaded files to. This is required if behavior is set to 'allow' +func (doPage Page) SetDownloadBehavior(behavior page.SetDownloadBehaviorBehavior, downloadPath *string) (err error) { + b := page.SetDownloadBehavior(behavior) + if downloadPath != nil { + b = b.WithDownloadPath(*downloadPath) + } + return b.Do(doPage.ctxWithExecutor) +} + +// SetLifecycleEventsEnabled controls whether page will emit lifecycle +// events. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setLifecycleEventsEnabled +// +// parameters: +// - `enabled`: If true, starts emitting lifecycle events. +func (doPage Page) SetLifecycleEventsEnabled(enabled bool) (err error) { + b := page.SetLifecycleEventsEnabled(enabled) + return b.Do(doPage.ctxWithExecutor) +} + +// StartScreencast starts sending each frame using the screencastFrame event. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-startScreencast +// +// parameters: +// - `format`: This can be nil. (Optional) Image compression format. +// - `quality`: This can be nil. (Optional) Compression quality from range [0..100]. +// - `maxWidth`: This can be nil. (Optional) Maximum screenshot width. +// - `maxHeight`: This can be nil. (Optional) Maximum screenshot height. +// - `everyNthFrame`: This can be nil. (Optional) Send every n-th frame. +func (doPage Page) StartScreencast(format *page.ScreencastFormat, quality *int64, maxWidth *int64, maxHeight *int64, everyNthFrame *int64) (err error) { + b := page.StartScreencast() + if format != nil { + b = b.WithFormat(*format) + } + if quality != nil { + b = b.WithQuality(*quality) + } + if maxWidth != nil { + b = b.WithMaxWidth(*maxWidth) + } + if maxHeight != nil { + b = b.WithMaxHeight(*maxHeight) + } + if everyNthFrame != nil { + b = b.WithEveryNthFrame(*everyNthFrame) + } + return b.Do(doPage.ctxWithExecutor) +} + +// StopLoading force the page stop all navigations and pending resource +// fetches. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-stopLoading +func (doPage Page) StopLoading() (err error) { + b := page.StopLoading() + return b.Do(doPage.ctxWithExecutor) +} + +// Crash crashes renderer on the IO thread, generates minidumps. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-crash +func (doPage Page) Crash() (err error) { + b := page.Crash() + return b.Do(doPage.ctxWithExecutor) +} + +// Close tries to close page, running its beforeunload hooks, if any. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-close +func (doPage Page) Close() (err error) { + b := page.Close() + return b.Do(doPage.ctxWithExecutor) +} + +// SetWebLifecycleState tries to update the web lifecycle state of the page. +// It will transition the page to the given state according to: +// https://github.com/WICG/web-lifecycle/. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setWebLifecycleState +// +// parameters: +// - `state`: Target lifecycle state +func (doPage Page) SetWebLifecycleState(state page.SetWebLifecycleStateState) (err error) { + b := page.SetWebLifecycleState(state) + return b.Do(doPage.ctxWithExecutor) +} + +// StopScreencast stops sending each frame in the screencastFrame. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-stopScreencast +func (doPage Page) StopScreencast() (err error) { + b := page.StopScreencast() + return b.Do(doPage.ctxWithExecutor) +} + +// SetProduceCompilationCache forces compilation cache to be generated for +// every subresource script. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setProduceCompilationCache +// +// parameters: +// - `enabled` +func (doPage Page) SetProduceCompilationCache(enabled bool) (err error) { + b := page.SetProduceCompilationCache(enabled) + return b.Do(doPage.ctxWithExecutor) +} + +// AddCompilationCache seeds compilation cache for given url. Compilation +// cache does not survive cross-process navigation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-addCompilationCache +// +// parameters: +// - `url` +// - `data`: Base64-encoded data +func (doPage Page) AddCompilationCache(url string, data string) (err error) { + b := page.AddCompilationCache(url, data) + return b.Do(doPage.ctxWithExecutor) +} + +// ClearCompilationCache clears seeded compilation cache. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-clearCompilationCache +func (doPage Page) ClearCompilationCache() (err error) { + b := page.ClearCompilationCache() + return b.Do(doPage.ctxWithExecutor) +} + +// GenerateTestReport generates a report for testing. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-generateTestReport +// +// parameters: +// - `message`: Message to be displayed in the report. +// - `group`: This can be nil. (Optional) Specifies the endpoint group to deliver the report to. +func (doPage Page) GenerateTestReport(message string, group *string) (err error) { + b := page.GenerateTestReport(message) + if group != nil { + b = b.WithGroup(*group) + } + return b.Do(doPage.ctxWithExecutor) +} + +// WaitForDebugger pauses page execution. Can be resumed using generic +// Runtime.runIfWaitingForDebugger. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-waitForDebugger +func (doPage Page) WaitForDebugger() (err error) { + b := page.WaitForDebugger() + return b.Do(doPage.ctxWithExecutor) +} + +// SetInterceptFileChooserDialog intercept file chooser requests and transfer +// control to protocol clients. When file chooser interception is enabled, +// native file chooser dialog is not shown. Instead, a protocol event +// Page.fileChooserOpened is emitted. File chooser can be handled with +// page.handleFileChooser command. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-setInterceptFileChooserDialog +// +// parameters: +// - `enabled` +func (doPage Page) SetInterceptFileChooserDialog(enabled bool) (err error) { + b := page.SetInterceptFileChooserDialog(enabled) + return b.Do(doPage.ctxWithExecutor) +} + +// HandleFileChooser accepts or cancels an intercepted file chooser dialog. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#method-handleFileChooser +// +// parameters: +// - `action` +// - `files`: This can be nil. (Optional) Array of absolute file paths to set, only respected with accept action. +func (doPage Page) HandleFileChooser(action page.HandleFileChooserAction, files []string) (err error) { + b := page.HandleFileChooser(action) + if files != nil { + b = b.WithFiles(files) + } + return b.Do(doPage.ctxWithExecutor) +} diff --git a/domain/performance.go b/domain/performance.go new file mode 100644 index 0000000..522b95e --- /dev/null +++ b/domain/performance.go @@ -0,0 +1,55 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/performance" +) + +// Performance executes a cdproto command under Performance domain. +type Performance struct { + ctxWithExecutor context.Context +} + +// Disable disable collecting and reporting metrics. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Performance#method-disable +func (doPerformance Performance) Disable() (err error) { + b := performance.Disable() + return b.Do(doPerformance.ctxWithExecutor) +} + +// Enable enable collecting and reporting metrics. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Performance#method-enable +func (doPerformance Performance) Enable() (err error) { + b := performance.Enable() + return b.Do(doPerformance.ctxWithExecutor) +} + +// SetTimeDomain sets time domain to use for collecting and reporting +// duration metrics. Note that this must be called before enabling metrics +// collection. Calling this method while metrics collection is enabled returns +// an error. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Performance#method-setTimeDomain +// +// parameters: +// - `timeDomain`: Time domain +func (doPerformance Performance) SetTimeDomain(timeDomain performance.SetTimeDomainTimeDomain) (err error) { + b := performance.SetTimeDomain(timeDomain) + return b.Do(doPerformance.ctxWithExecutor) +} + +// GetMetrics retrieve current values of run-time metrics. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Performance#method-getMetrics +// +// returns: +// - `retMetrics`: Current values for run-time metrics. +func (doPerformance Performance) GetMetrics() (retMetrics []*performance.Metric, err error) { + b := performance.GetMetrics() + return b.Do(doPerformance.ctxWithExecutor) +} diff --git a/domain/profiler.go b/domain/profiler.go new file mode 100644 index 0000000..ce6a36e --- /dev/null +++ b/domain/profiler.go @@ -0,0 +1,142 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/profiler" +) + +// Profiler executes a cdproto command under Profiler domain. +type Profiler struct { + ctxWithExecutor context.Context +} + +// Disable [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-disable +func (doProfiler Profiler) Disable() (err error) { + b := profiler.Disable() + return b.Do(doProfiler.ctxWithExecutor) +} + +// Enable [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-enable +func (doProfiler Profiler) Enable() (err error) { + b := profiler.Enable() + return b.Do(doProfiler.ctxWithExecutor) +} + +// GetBestEffortCoverage collect coverage data for the current isolate. The +// coverage data may be incomplete due to garbage collection. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-getBestEffortCoverage +// +// returns: +// - `retResult`: Coverage data for the current isolate. +func (doProfiler Profiler) GetBestEffortCoverage() (retResult []*profiler.ScriptCoverage, err error) { + b := profiler.GetBestEffortCoverage() + return b.Do(doProfiler.ctxWithExecutor) +} + +// SetSamplingInterval changes CPU profiler sampling interval. Must be called +// before CPU profiles recording started. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-setSamplingInterval +// +// parameters: +// - `interval`: New sampling interval in microseconds. +func (doProfiler Profiler) SetSamplingInterval(interval int64) (err error) { + b := profiler.SetSamplingInterval(interval) + return b.Do(doProfiler.ctxWithExecutor) +} + +// Start [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-start +func (doProfiler Profiler) Start() (err error) { + b := profiler.Start() + return b.Do(doProfiler.ctxWithExecutor) +} + +// StartPreciseCoverage enable precise code coverage. Coverage data for +// JavaScript executed before enabling precise code coverage may be incomplete. +// Enabling prevents running optimized code and resets execution counters. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-startPreciseCoverage +// +// parameters: +// - `callCount`: This can be nil. (Optional) Collect accurate call counts beyond simple 'covered' or 'not covered'. +// - `detailed`: This can be nil. (Optional) Collect block-based coverage. +func (doProfiler Profiler) StartPreciseCoverage(callCount *bool, detailed *bool) (err error) { + b := profiler.StartPreciseCoverage() + if callCount != nil { + b = b.WithCallCount(*callCount) + } + if detailed != nil { + b = b.WithDetailed(*detailed) + } + return b.Do(doProfiler.ctxWithExecutor) +} + +// StartTypeProfile enable type profile. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-startTypeProfile +func (doProfiler Profiler) StartTypeProfile() (err error) { + b := profiler.StartTypeProfile() + return b.Do(doProfiler.ctxWithExecutor) +} + +// Stop [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-stop +// +// returns: +// - `retProfile`: Recorded profile. +func (doProfiler Profiler) Stop() (retProfile *profiler.Profile, err error) { + b := profiler.Stop() + return b.Do(doProfiler.ctxWithExecutor) +} + +// StopPreciseCoverage disable precise code coverage. Disabling releases +// unnecessary execution count records and allows executing optimized code. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-stopPreciseCoverage +func (doProfiler Profiler) StopPreciseCoverage() (err error) { + b := profiler.StopPreciseCoverage() + return b.Do(doProfiler.ctxWithExecutor) +} + +// StopTypeProfile disable type profile. Disabling releases type profile data +// collected so far. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-stopTypeProfile +func (doProfiler Profiler) StopTypeProfile() (err error) { + b := profiler.StopTypeProfile() + return b.Do(doProfiler.ctxWithExecutor) +} + +// TakePreciseCoverage collect coverage data for the current isolate, and +// resets execution counters. Precise code coverage needs to have started. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-takePreciseCoverage +// +// returns: +// - `retResult`: Coverage data for the current isolate. +func (doProfiler Profiler) TakePreciseCoverage() (retResult []*profiler.ScriptCoverage, err error) { + b := profiler.TakePreciseCoverage() + return b.Do(doProfiler.ctxWithExecutor) +} + +// TakeTypeProfile collect type profile. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Profiler#method-takeTypeProfile +// +// returns: +// - `retResult`: Type profile for all scripts since startTypeProfile() was turned on. +func (doProfiler Profiler) TakeTypeProfile() (retResult []*profiler.ScriptTypeProfile, err error) { + b := profiler.TakeTypeProfile() + return b.Do(doProfiler.ctxWithExecutor) +} diff --git a/domain/runtime.go b/domain/runtime.go new file mode 100644 index 0000000..dd6d0ef --- /dev/null +++ b/domain/runtime.go @@ -0,0 +1,425 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/runtime" +) + +// Runtime executes a cdproto command under Runtime domain. +type Runtime struct { + ctxWithExecutor context.Context +} + +// AwaitPromise add handler to promise with given promise object id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-awaitPromise +// +// parameters: +// - `promiseObjectID`: Identifier of the promise. +// - `returnByValue`: This can be nil. (Optional) Whether the result is expected to be a JSON object that should be sent by value. +// - `generatePreview`: This can be nil. (Optional) Whether preview should be generated for the result. +// +// returns: +// - `retResult`: Promise result. Will contain rejected value if promise was rejected. +// - `retExceptionDetails`: Exception details if stack strace is available. +func (doRuntime Runtime) AwaitPromise(promiseObjectID runtime.RemoteObjectID, returnByValue *bool, generatePreview *bool) (retResult *runtime.RemoteObject, retExceptionDetails *runtime.ExceptionDetails, err error) { + b := runtime.AwaitPromise(promiseObjectID) + if returnByValue != nil { + b = b.WithReturnByValue(*returnByValue) + } + if generatePreview != nil { + b = b.WithGeneratePreview(*generatePreview) + } + return b.Do(doRuntime.ctxWithExecutor) +} + +// CallFunctionOn calls function with given declaration on the given object. +// Object group of the result is inherited from the target object. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-callFunctionOn +// +// parameters: +// - `functionDeclaration`: Declaration of the function to call. +// - `objectID`: This can be nil. (Optional) Identifier of the object to call function on. Either objectId or executionContextId should be specified. +// - `arguments`: This can be nil. (Optional) Call arguments. All call arguments must belong to the same JavaScript world as the target object. +// - `silent`: This can be nil. (Optional) In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. +// - `returnByValue`: This can be nil. (Optional) Whether the result is expected to be a JSON object which should be sent by value. +// - `generatePreview`: This can be nil. (Optional) Whether preview should be generated for the result. +// - `userGesture`: This can be nil. (Optional) Whether execution should be treated as initiated by user in the UI. +// - `awaitPromise`: This can be nil. (Optional) Whether execution should await for resulting value and return once awaited promise is resolved. +// - `executionContextID`: This can be nil. (Optional) Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. +// - `objectGroup`: This can be nil. (Optional) Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. +// +// returns: +// - `retResult`: Call result. +// - `retExceptionDetails`: Exception details. +func (doRuntime Runtime) CallFunctionOn(functionDeclaration string, objectID *runtime.RemoteObjectID, arguments []*runtime.CallArgument, silent *bool, returnByValue *bool, generatePreview *bool, userGesture *bool, awaitPromise *bool, executionContextID *runtime.ExecutionContextID, objectGroup *string) (retResult *runtime.RemoteObject, retExceptionDetails *runtime.ExceptionDetails, err error) { + b := runtime.CallFunctionOn(functionDeclaration) + if objectID != nil { + b = b.WithObjectID(*objectID) + } + if arguments != nil { + b = b.WithArguments(arguments) + } + if silent != nil { + b = b.WithSilent(*silent) + } + if returnByValue != nil { + b = b.WithReturnByValue(*returnByValue) + } + if generatePreview != nil { + b = b.WithGeneratePreview(*generatePreview) + } + if userGesture != nil { + b = b.WithUserGesture(*userGesture) + } + if awaitPromise != nil { + b = b.WithAwaitPromise(*awaitPromise) + } + if executionContextID != nil { + b = b.WithExecutionContextID(*executionContextID) + } + if objectGroup != nil { + b = b.WithObjectGroup(*objectGroup) + } + return b.Do(doRuntime.ctxWithExecutor) +} + +// CompileScript compiles expression. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-compileScript +// +// parameters: +// - `expression`: Expression to compile. +// - `sourceURL`: Source url to be set for the script. +// - `persistScript`: Specifies whether the compiled script should be persisted. +// - `executionContextID`: This can be nil. (Optional) Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. +// +// returns: +// - `retScriptID`: Id of the script. +// - `retExceptionDetails`: Exception details. +func (doRuntime Runtime) CompileScript(expression string, sourceURL string, persistScript bool, executionContextID *runtime.ExecutionContextID) (retScriptID runtime.ScriptID, retExceptionDetails *runtime.ExceptionDetails, err error) { + b := runtime.CompileScript(expression, sourceURL, persistScript) + if executionContextID != nil { + b = b.WithExecutionContextID(*executionContextID) + } + return b.Do(doRuntime.ctxWithExecutor) +} + +// Disable disables reporting of execution contexts creation. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-disable +func (doRuntime Runtime) Disable() (err error) { + b := runtime.Disable() + return b.Do(doRuntime.ctxWithExecutor) +} + +// DiscardConsoleEntries discards collected exceptions and console API calls. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-discardConsoleEntries +func (doRuntime Runtime) DiscardConsoleEntries() (err error) { + b := runtime.DiscardConsoleEntries() + return b.Do(doRuntime.ctxWithExecutor) +} + +// Enable enables reporting of execution contexts creation by means of +// executionContextCreated event. When the reporting gets enabled the event will +// be sent immediately for each existing execution context. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-enable +func (doRuntime Runtime) Enable() (err error) { + b := runtime.Enable() + return b.Do(doRuntime.ctxWithExecutor) +} + +// Evaluate evaluates expression on global object. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-evaluate +// +// parameters: +// - `expression`: Expression to evaluate. +// - `objectGroup`: This can be nil. (Optional) Symbolic group name that can be used to release multiple objects. +// - `includeCommandLineAPI`: This can be nil. (Optional) Determines whether Command Line API should be available during the evaluation. +// - `silent`: This can be nil. (Optional) In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. +// - `contextID`: This can be nil. (Optional) Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. +// - `returnByValue`: This can be nil. (Optional) Whether the result is expected to be a JSON object that should be sent by value. +// - `generatePreview`: This can be nil. (Optional) Whether preview should be generated for the result. +// - `userGesture`: This can be nil. (Optional) Whether execution should be treated as initiated by user in the UI. +// - `awaitPromise`: This can be nil. (Optional) Whether execution should await for resulting value and return once awaited promise is resolved. +// - `throwOnSideEffect`: This can be nil. (Optional) Whether to throw an exception if side effect cannot be ruled out during evaluation. This implies disableBreaks below. +// - `timeout`: This can be nil. (Optional) Terminate execution after timing out (number of milliseconds). +// - `disableBreaks`: This can be nil. (Optional) Disable breakpoints during execution. +// +// returns: +// - `retResult`: Evaluation result. +// - `retExceptionDetails`: Exception details. +func (doRuntime Runtime) Evaluate(expression string, objectGroup *string, includeCommandLineAPI *bool, silent *bool, contextID *runtime.ExecutionContextID, returnByValue *bool, generatePreview *bool, userGesture *bool, awaitPromise *bool, throwOnSideEffect *bool, timeout *runtime.TimeDelta, disableBreaks *bool) (retResult *runtime.RemoteObject, retExceptionDetails *runtime.ExceptionDetails, err error) { + b := runtime.Evaluate(expression) + if objectGroup != nil { + b = b.WithObjectGroup(*objectGroup) + } + if includeCommandLineAPI != nil { + b = b.WithIncludeCommandLineAPI(*includeCommandLineAPI) + } + if silent != nil { + b = b.WithSilent(*silent) + } + if contextID != nil { + b = b.WithContextID(*contextID) + } + if returnByValue != nil { + b = b.WithReturnByValue(*returnByValue) + } + if generatePreview != nil { + b = b.WithGeneratePreview(*generatePreview) + } + if userGesture != nil { + b = b.WithUserGesture(*userGesture) + } + if awaitPromise != nil { + b = b.WithAwaitPromise(*awaitPromise) + } + if throwOnSideEffect != nil { + b = b.WithThrowOnSideEffect(*throwOnSideEffect) + } + if timeout != nil { + b = b.WithTimeout(*timeout) + } + if disableBreaks != nil { + b = b.WithDisableBreaks(*disableBreaks) + } + return b.Do(doRuntime.ctxWithExecutor) +} + +// GetIsolateID returns the isolate id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getIsolateId +// +// returns: +// - `retID`: The isolate id. +func (doRuntime Runtime) GetIsolateID() (retID string, err error) { + b := runtime.GetIsolateID() + return b.Do(doRuntime.ctxWithExecutor) +} + +// GetHeapUsage returns the JavaScript heap usage. It is the total usage of +// the corresponding isolate not scoped to a particular Runtime. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getHeapUsage +// +// returns: +// - `retUsedSize`: Used heap size in bytes. +// - `retTotalSize`: Allocated heap size in bytes. +func (doRuntime Runtime) GetHeapUsage() (retUsedSize float64, retTotalSize float64, err error) { + b := runtime.GetHeapUsage() + return b.Do(doRuntime.ctxWithExecutor) +} + +// GetProperties returns properties of a given object. Object group of the +// result is inherited from the target object. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-getProperties +// +// parameters: +// - `objectID`: Identifier of the object to return properties for. +// - `ownProperties`: This can be nil. (Optional) If true, returns properties belonging only to the element itself, not to its prototype chain. +// - `accessorPropertiesOnly`: This can be nil. (Optional) If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. +// - `generatePreview`: This can be nil. (Optional) Whether preview should be generated for the results. +// +// returns: +// - `retResult`: Object properties. +// - `retInternalProperties`: Internal object properties (only of the element itself). +// - `retPrivateProperties`: Object private properties. +// - `retExceptionDetails`: Exception details. +func (doRuntime Runtime) GetProperties(objectID runtime.RemoteObjectID, ownProperties *bool, accessorPropertiesOnly *bool, generatePreview *bool) (retResult []*runtime.PropertyDescriptor, retInternalProperties []*runtime.InternalPropertyDescriptor, retPrivateProperties []*runtime.PrivatePropertyDescriptor, retExceptionDetails *runtime.ExceptionDetails, err error) { + b := runtime.GetProperties(objectID) + if ownProperties != nil { + b = b.WithOwnProperties(*ownProperties) + } + if accessorPropertiesOnly != nil { + b = b.WithAccessorPropertiesOnly(*accessorPropertiesOnly) + } + if generatePreview != nil { + b = b.WithGeneratePreview(*generatePreview) + } + return b.Do(doRuntime.ctxWithExecutor) +} + +// GlobalLexicalScopeNames returns all let, const and class variables from +// global scope. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-globalLexicalScopeNames +// +// parameters: +// - `executionContextID`: This can be nil. (Optional) Specifies in which execution context to lookup global scope variables. +// +// returns: +// - `retNames` +func (doRuntime Runtime) GlobalLexicalScopeNames(executionContextID *runtime.ExecutionContextID) (retNames []string, err error) { + b := runtime.GlobalLexicalScopeNames() + if executionContextID != nil { + b = b.WithExecutionContextID(*executionContextID) + } + return b.Do(doRuntime.ctxWithExecutor) +} + +// QueryObjects [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-queryObjects +// +// parameters: +// - `prototypeObjectID`: Identifier of the prototype to return objects for. +// - `objectGroup`: This can be nil. (Optional) Symbolic group name that can be used to release the results. +// +// returns: +// - `retObjects`: Array with objects. +func (doRuntime Runtime) QueryObjects(prototypeObjectID runtime.RemoteObjectID, objectGroup *string) (retObjects *runtime.RemoteObject, err error) { + b := runtime.QueryObjects(prototypeObjectID) + if objectGroup != nil { + b = b.WithObjectGroup(*objectGroup) + } + return b.Do(doRuntime.ctxWithExecutor) +} + +// ReleaseObject releases remote object with given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-releaseObject +// +// parameters: +// - `objectID`: Identifier of the object to release. +func (doRuntime Runtime) ReleaseObject(objectID runtime.RemoteObjectID) (err error) { + b := runtime.ReleaseObject(objectID) + return b.Do(doRuntime.ctxWithExecutor) +} + +// ReleaseObjectGroup releases all remote objects that belong to a given +// group. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-releaseObjectGroup +// +// parameters: +// - `objectGroup`: Symbolic object group name. +func (doRuntime Runtime) ReleaseObjectGroup(objectGroup string) (err error) { + b := runtime.ReleaseObjectGroup(objectGroup) + return b.Do(doRuntime.ctxWithExecutor) +} + +// RunIfWaitingForDebugger tells inspected instance to run if it was waiting +// for debugger to attach. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runIfWaitingForDebugger +func (doRuntime Runtime) RunIfWaitingForDebugger() (err error) { + b := runtime.RunIfWaitingForDebugger() + return b.Do(doRuntime.ctxWithExecutor) +} + +// RunScript runs script with given id in a given context. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-runScript +// +// parameters: +// - `scriptID`: Id of the script to run. +// - `executionContextID`: This can be nil. (Optional) Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. +// - `objectGroup`: This can be nil. (Optional) Symbolic group name that can be used to release multiple objects. +// - `silent`: This can be nil. (Optional) In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. +// - `includeCommandLineAPI`: This can be nil. (Optional) Determines whether Command Line API should be available during the evaluation. +// - `returnByValue`: This can be nil. (Optional) Whether the result is expected to be a JSON object which should be sent by value. +// - `generatePreview`: This can be nil. (Optional) Whether preview should be generated for the result. +// - `awaitPromise`: This can be nil. (Optional) Whether execution should await for resulting value and return once awaited promise is resolved. +// +// returns: +// - `retResult`: Run result. +// - `retExceptionDetails`: Exception details. +func (doRuntime Runtime) RunScript(scriptID runtime.ScriptID, executionContextID *runtime.ExecutionContextID, objectGroup *string, silent *bool, includeCommandLineAPI *bool, returnByValue *bool, generatePreview *bool, awaitPromise *bool) (retResult *runtime.RemoteObject, retExceptionDetails *runtime.ExceptionDetails, err error) { + b := runtime.RunScript(scriptID) + if executionContextID != nil { + b = b.WithExecutionContextID(*executionContextID) + } + if objectGroup != nil { + b = b.WithObjectGroup(*objectGroup) + } + if silent != nil { + b = b.WithSilent(*silent) + } + if includeCommandLineAPI != nil { + b = b.WithIncludeCommandLineAPI(*includeCommandLineAPI) + } + if returnByValue != nil { + b = b.WithReturnByValue(*returnByValue) + } + if generatePreview != nil { + b = b.WithGeneratePreview(*generatePreview) + } + if awaitPromise != nil { + b = b.WithAwaitPromise(*awaitPromise) + } + return b.Do(doRuntime.ctxWithExecutor) +} + +// SetCustomObjectFormatterEnabled [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setCustomObjectFormatterEnabled +// +// parameters: +// - `enabled` +func (doRuntime Runtime) SetCustomObjectFormatterEnabled(enabled bool) (err error) { + b := runtime.SetCustomObjectFormatterEnabled(enabled) + return b.Do(doRuntime.ctxWithExecutor) +} + +// SetMaxCallStackSizeToCapture [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-setMaxCallStackSizeToCapture +// +// parameters: +// - `size` +func (doRuntime Runtime) SetMaxCallStackSizeToCapture(size int64) (err error) { + b := runtime.SetMaxCallStackSizeToCapture(size) + return b.Do(doRuntime.ctxWithExecutor) +} + +// TerminateExecution terminate current or next JavaScript execution. Will +// cancel the termination when the outer-most script execution ends. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-terminateExecution +func (doRuntime Runtime) TerminateExecution() (err error) { + b := runtime.TerminateExecution() + return b.Do(doRuntime.ctxWithExecutor) +} + +// AddBinding if executionContextId is empty, adds binding with the given +// name on the global objects of all inspected contexts, including those created +// later, bindings survive reloads. If executionContextId is specified, adds +// binding only on global object of given execution context. Binding function +// takes exactly one argument, this argument should be string, in case of any +// other input, function throws an exception. Each binding function call +// produces Runtime.bindingCalled notification. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-addBinding +// +// parameters: +// - `name` +// - `executionContextID` +func (doRuntime Runtime) AddBinding(name string, executionContextID *runtime.ExecutionContextID) (err error) { + b := runtime.AddBinding(name) + if executionContextID != nil { + b = b.WithExecutionContextID(*executionContextID) + } + return b.Do(doRuntime.ctxWithExecutor) +} + +// RemoveBinding this method does not remove binding function from global +// object but unsubscribes current runtime agent from Runtime.bindingCalled +// notifications. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Runtime#method-removeBinding +// +// parameters: +// - `name` +func (doRuntime Runtime) RemoveBinding(name string) (err error) { + b := runtime.RemoveBinding(name) + return b.Do(doRuntime.ctxWithExecutor) +} diff --git a/domain/security.go b/domain/security.go new file mode 100644 index 0000000..42bf55b --- /dev/null +++ b/domain/security.go @@ -0,0 +1,42 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/security" +) + +// Security executes a cdproto command under Security domain. +type Security struct { + ctxWithExecutor context.Context +} + +// Disable disables tracking security state changes. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Security#method-disable +func (doSecurity Security) Disable() (err error) { + b := security.Disable() + return b.Do(doSecurity.ctxWithExecutor) +} + +// Enable enables tracking security state changes. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Security#method-enable +func (doSecurity Security) Enable() (err error) { + b := security.Enable() + return b.Do(doSecurity.ctxWithExecutor) +} + +// SetIgnoreCertificateErrors enable/disable whether all certificate errors +// should be ignored. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setIgnoreCertificateErrors +// +// parameters: +// - `ignore`: If true, all certificate errors will be ignored. +func (doSecurity Security) SetIgnoreCertificateErrors(ignore bool) (err error) { + b := security.SetIgnoreCertificateErrors(ignore) + return b.Do(doSecurity.ctxWithExecutor) +} diff --git a/domain/serviceworker.go b/domain/serviceworker.go new file mode 100644 index 0000000..c5ff47d --- /dev/null +++ b/domain/serviceworker.go @@ -0,0 +1,155 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/serviceworker" +) + +// ServiceWorker executes a cdproto command under ServiceWorker domain. +type ServiceWorker struct { + ctxWithExecutor context.Context +} + +// DeliverPushMessage [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-deliverPushMessage +// +// parameters: +// - `origin` +// - `registrationID` +// - `data` +func (doServiceWorker ServiceWorker) DeliverPushMessage(origin string, registrationID serviceworker.RegistrationID, data string) (err error) { + b := serviceworker.DeliverPushMessage(origin, registrationID, data) + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// Disable [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-disable +func (doServiceWorker ServiceWorker) Disable() (err error) { + b := serviceworker.Disable() + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// DispatchSyncEvent [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-dispatchSyncEvent +// +// parameters: +// - `origin` +// - `registrationID` +// - `tag` +// - `lastChance` +func (doServiceWorker ServiceWorker) DispatchSyncEvent(origin string, registrationID serviceworker.RegistrationID, tag string, lastChance bool) (err error) { + b := serviceworker.DispatchSyncEvent(origin, registrationID, tag, lastChance) + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// DispatchPeriodicSyncEvent [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-dispatchPeriodicSyncEvent +// +// parameters: +// - `origin` +// - `registrationID` +// - `tag` +func (doServiceWorker ServiceWorker) DispatchPeriodicSyncEvent(origin string, registrationID serviceworker.RegistrationID, tag string) (err error) { + b := serviceworker.DispatchPeriodicSyncEvent(origin, registrationID, tag) + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// Enable [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-enable +func (doServiceWorker ServiceWorker) Enable() (err error) { + b := serviceworker.Enable() + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// InspectWorker [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-inspectWorker +// +// parameters: +// - `versionID` +func (doServiceWorker ServiceWorker) InspectWorker(versionID string) (err error) { + b := serviceworker.InspectWorker(versionID) + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// SetForceUpdateOnPageLoad [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-setForceUpdateOnPageLoad +// +// parameters: +// - `forceUpdateOnPageLoad` +func (doServiceWorker ServiceWorker) SetForceUpdateOnPageLoad(forceUpdateOnPageLoad bool) (err error) { + b := serviceworker.SetForceUpdateOnPageLoad(forceUpdateOnPageLoad) + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// SkipWaiting [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-skipWaiting +// +// parameters: +// - `scopeURL` +func (doServiceWorker ServiceWorker) SkipWaiting(scopeURL string) (err error) { + b := serviceworker.SkipWaiting(scopeURL) + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// StartWorker [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-startWorker +// +// parameters: +// - `scopeURL` +func (doServiceWorker ServiceWorker) StartWorker(scopeURL string) (err error) { + b := serviceworker.StartWorker(scopeURL) + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// StopAllWorkers [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-stopAllWorkers +func (doServiceWorker ServiceWorker) StopAllWorkers() (err error) { + b := serviceworker.StopAllWorkers() + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// StopWorker [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-stopWorker +// +// parameters: +// - `versionID` +func (doServiceWorker ServiceWorker) StopWorker(versionID string) (err error) { + b := serviceworker.StopWorker(versionID) + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// Unregister [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-unregister +// +// parameters: +// - `scopeURL` +func (doServiceWorker ServiceWorker) Unregister(scopeURL string) (err error) { + b := serviceworker.Unregister(scopeURL) + return b.Do(doServiceWorker.ctxWithExecutor) +} + +// UpdateRegistration [no description]. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker#method-updateRegistration +// +// parameters: +// - `scopeURL` +func (doServiceWorker ServiceWorker) UpdateRegistration(scopeURL string) (err error) { + b := serviceworker.UpdateRegistration(scopeURL) + return b.Do(doServiceWorker.ctxWithExecutor) +} diff --git a/domain/storage.go b/domain/storage.go new file mode 100644 index 0000000..3df72f6 --- /dev/null +++ b/domain/storage.go @@ -0,0 +1,90 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/storage" +) + +// Storage executes a cdproto command under Storage domain. +type Storage struct { + ctxWithExecutor context.Context +} + +// ClearDataForOrigin clears storage for origin. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-clearDataForOrigin +// +// parameters: +// - `origin`: Security origin. +// - `storageTypes`: Comma separated list of StorageType to clear. +func (doStorage Storage) ClearDataForOrigin(origin string, storageTypes string) (err error) { + b := storage.ClearDataForOrigin(origin, storageTypes) + return b.Do(doStorage.ctxWithExecutor) +} + +// GetUsageAndQuota returns usage and quota in bytes. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-getUsageAndQuota +// +// parameters: +// - `origin`: Security origin. +// +// returns: +// - `retUsage`: Storage usage (bytes). +// - `retQuota`: Storage quota (bytes). +// - `retUsageBreakdown`: Storage usage per type (bytes). +func (doStorage Storage) GetUsageAndQuota(origin string) (retUsage float64, retQuota float64, retUsageBreakdown []*storage.UsageForType, err error) { + b := storage.GetUsageAndQuota(origin) + return b.Do(doStorage.ctxWithExecutor) +} + +// TrackCacheStorageForOrigin registers origin to be notified when an update +// occurs to its cache storage list. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackCacheStorageForOrigin +// +// parameters: +// - `origin`: Security origin. +func (doStorage Storage) TrackCacheStorageForOrigin(origin string) (err error) { + b := storage.TrackCacheStorageForOrigin(origin) + return b.Do(doStorage.ctxWithExecutor) +} + +// TrackIndexedDBForOrigin registers origin to be notified when an update +// occurs to its IndexedDB. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-trackIndexedDBForOrigin +// +// parameters: +// - `origin`: Security origin. +func (doStorage Storage) TrackIndexedDBForOrigin(origin string) (err error) { + b := storage.TrackIndexedDBForOrigin(origin) + return b.Do(doStorage.ctxWithExecutor) +} + +// UntrackCacheStorageForOrigin unregisters origin from receiving +// notifications for cache storage. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackCacheStorageForOrigin +// +// parameters: +// - `origin`: Security origin. +func (doStorage Storage) UntrackCacheStorageForOrigin(origin string) (err error) { + b := storage.UntrackCacheStorageForOrigin(origin) + return b.Do(doStorage.ctxWithExecutor) +} + +// UntrackIndexedDBForOrigin unregisters origin from receiving notifications +// for IndexedDB. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Storage#method-untrackIndexedDBForOrigin +// +// parameters: +// - `origin`: Security origin. +func (doStorage Storage) UntrackIndexedDBForOrigin(origin string) (err error) { + b := storage.UntrackIndexedDBForOrigin(origin) + return b.Do(doStorage.ctxWithExecutor) +} diff --git a/domain/systeminfo.go b/domain/systeminfo.go new file mode 100644 index 0000000..43befd3 --- /dev/null +++ b/domain/systeminfo.go @@ -0,0 +1,39 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/systeminfo" +) + +// SystemInfo executes a cdproto command under SystemInfo domain. +type SystemInfo struct { + ctxWithExecutor context.Context +} + +// GetInfo returns information about the system. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo#method-getInfo +// +// returns: +// - `retGpu`: Information about the GPUs on the system. +// - `retModelName`: A platform-dependent description of the model of the machine. On Mac OS, this is, for example, 'MacBookPro'. Will be the empty string if not supported. +// - `retModelVersion`: A platform-dependent description of the version of the machine. On Mac OS, this is, for example, '10.1'. Will be the empty string if not supported. +// - `retCommandLine`: The command line string used to launch the browser. Will be the empty string if not supported. +func (doSystemInfo SystemInfo) GetInfo() (retGpu *systeminfo.GPUInfo, retModelName string, retModelVersion string, retCommandLine string, err error) { + b := systeminfo.GetInfo() + return b.Do(doSystemInfo.ctxWithExecutor) +} + +// GetProcessInfo returns information about all running processes. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo#method-getProcessInfo +// +// returns: +// - `retProcessInfo`: An array of process info blocks. +func (doSystemInfo SystemInfo) GetProcessInfo() (retProcessInfo []*systeminfo.ProcessInfo, err error) { + b := systeminfo.GetProcessInfo() + return b.Do(doSystemInfo.ctxWithExecutor) +} diff --git a/domain/target.go b/domain/target.go new file mode 100644 index 0000000..08ba83f --- /dev/null +++ b/domain/target.go @@ -0,0 +1,253 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/target" +) + +// Target executes a cdproto command under Target domain. +type Target struct { + ctxWithExecutor context.Context +} + +// ActivateTarget activates (focuses) the target. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-activateTarget +// +// parameters: +// - `targetID` +func (doTarget Target) ActivateTarget(targetID target.ID) (err error) { + b := target.ActivateTarget(targetID) + return b.Do(doTarget.ctxWithExecutor) +} + +// AttachToTarget attaches to the target with given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-attachToTarget +// +// parameters: +// - `targetID` +// - `flatten`: This can be nil. (Optional) Enables "flat" access to the session via specifying sessionId attribute in the commands. We plan to make this the default, deprecate non-flattened mode, and eventually retire it. See crbug.com/991325. +// +// returns: +// - `retSessionID`: Id assigned to the session. +func (doTarget Target) AttachToTarget(targetID target.ID, flatten *bool) (retSessionID target.SessionID, err error) { + b := target.AttachToTarget(targetID) + if flatten != nil { + b = b.WithFlatten(*flatten) + } + return b.Do(doTarget.ctxWithExecutor) +} + +// AttachToBrowserTarget attaches to the browser target, only uses flat +// sessionId mode. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-attachToBrowserTarget +// +// returns: +// - `retSessionID`: Id assigned to the session. +func (doTarget Target) AttachToBrowserTarget() (retSessionID target.SessionID, err error) { + b := target.AttachToBrowserTarget() + return b.Do(doTarget.ctxWithExecutor) +} + +// CloseTarget closes the target. If the target is a page that gets closed +// too. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-closeTarget +// +// parameters: +// - `targetID` +// +// returns: +// - `retSuccess` +func (doTarget Target) CloseTarget(targetID target.ID) (retSuccess bool, err error) { + b := target.CloseTarget(targetID) + return b.Do(doTarget.ctxWithExecutor) +} + +// ExposeDevToolsProtocol inject object to the target's main frame that +// provides a communication channel with browser target. Injected object will be +// available as window[bindingName]. The object has the follwing API: - +// binding.send(json) - a method to send messages over the remote debugging +// protocol - binding.onmessage = json => handleMessage(json) - a callback that +// will be called for the protocol notifications and command responses. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-exposeDevToolsProtocol +// +// parameters: +// - `targetID` +// - `bindingName`: This can be nil. (Optional) Binding name, 'cdp' if not specified. +func (doTarget Target) ExposeDevToolsProtocol(targetID target.ID, bindingName *string) (err error) { + b := target.ExposeDevToolsProtocol(targetID) + if bindingName != nil { + b = b.WithBindingName(*bindingName) + } + return b.Do(doTarget.ctxWithExecutor) +} + +// CreateBrowserContext creates a new empty BrowserContext. Similar to an +// incognito profile but you can have more than one. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-createBrowserContext +// +// returns: +// - `retBrowserContextID`: The id of the context created. +func (doTarget Target) CreateBrowserContext() (retBrowserContextID target.BrowserContextID, err error) { + b := target.CreateBrowserContext() + return b.Do(doTarget.ctxWithExecutor) +} + +// GetBrowserContexts returns all browser contexts created with +// Target.createBrowserContext method. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-getBrowserContexts +// +// returns: +// - `retBrowserContextIds`: An array of browser context ids. +func (doTarget Target) GetBrowserContexts() (retBrowserContextIds []target.BrowserContextID, err error) { + b := target.GetBrowserContexts() + return b.Do(doTarget.ctxWithExecutor) +} + +// CreateTarget creates a new page. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-createTarget +// +// parameters: +// - `url`: The initial URL the page will be navigated to. +// - `width`: This can be nil. (Optional) Frame width in DIP (headless chrome only). +// - `height`: This can be nil. (Optional) Frame height in DIP (headless chrome only). +// - `browserContextID`: This can be nil. (Optional) The browser context to create the page in. +// - `enableBeginFrameControl`: This can be nil. (Optional) Whether BeginFrames for this target will be controlled via DevTools (headless chrome only, not supported on MacOS yet, false by default). +// - `newWindow`: This can be nil. (Optional) Whether to create a new Window or Tab (chrome-only, false by default). +// - `background`: This can be nil. (Optional) Whether to create the target in background or foreground (chrome-only, false by default). +// +// returns: +// - `retTargetID`: The id of the page opened. +func (doTarget Target) CreateTarget(url string, width *int64, height *int64, browserContextID *target.BrowserContextID, enableBeginFrameControl *bool, newWindow *bool, background *bool) (retTargetID target.ID, err error) { + b := target.CreateTarget(url) + if width != nil { + b = b.WithWidth(*width) + } + if height != nil { + b = b.WithHeight(*height) + } + if browserContextID != nil { + b = b.WithBrowserContextID(*browserContextID) + } + if enableBeginFrameControl != nil { + b = b.WithEnableBeginFrameControl(*enableBeginFrameControl) + } + if newWindow != nil { + b = b.WithNewWindow(*newWindow) + } + if background != nil { + b = b.WithBackground(*background) + } + return b.Do(doTarget.ctxWithExecutor) +} + +// DetachFromTarget detaches session with given id. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-detachFromTarget +// +// parameters: +// - `sessionID`: This can be nil. (Optional) Session to detach. +func (doTarget Target) DetachFromTarget(sessionID *target.SessionID) (err error) { + b := target.DetachFromTarget() + if sessionID != nil { + b = b.WithSessionID(*sessionID) + } + return b.Do(doTarget.ctxWithExecutor) +} + +// DisposeBrowserContext deletes a BrowserContext. All the belonging pages +// will be closed without calling their beforeunload hooks. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-disposeBrowserContext +// +// parameters: +// - `browserContextID` +func (doTarget Target) DisposeBrowserContext(browserContextID target.BrowserContextID) (err error) { + b := target.DisposeBrowserContext(browserContextID) + return b.Do(doTarget.ctxWithExecutor) +} + +// GetTargetInfo returns information about a target. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-getTargetInfo +// +// parameters: +// - `targetID` +// +// returns: +// - `retTargetInfo` +func (doTarget Target) GetTargetInfo(targetID *target.ID) (retTargetInfo *target.Info, err error) { + b := target.GetTargetInfo() + if targetID != nil { + b = b.WithTargetID(*targetID) + } + return b.Do(doTarget.ctxWithExecutor) +} + +// GetTargets retrieves a list of available targets. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-getTargets +// +// returns: +// - `retTargetInfos`: The list of targets. +func (doTarget Target) GetTargets() (retTargetInfos []*target.Info, err error) { + b := target.GetTargets() + return b.Do(doTarget.ctxWithExecutor) +} + +// SetAutoAttach controls whether to automatically attach to new targets +// which are considered to be related to this one. When turned on, attaches to +// all existing related targets as well. When turned off, automatically detaches +// from all currently attached targets. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-setAutoAttach +// +// parameters: +// - `autoAttach`: Whether to auto-attach to related targets. +// - `waitForDebuggerOnStart`: Whether to pause new targets when attaching to them. Use Runtime.runIfWaitingForDebugger to run paused targets. +// - `flatten`: This can be nil. (Optional) Enables "flat" access to the session via specifying sessionId attribute in the commands. We plan to make this the default, deprecate non-flattened mode, and eventually retire it. See crbug.com/991325. +// - `windowOpen`: This can be nil. (Optional) Auto-attach to the targets created via window.open from current target. +func (doTarget Target) SetAutoAttach(autoAttach bool, waitForDebuggerOnStart bool, flatten *bool, windowOpen *bool) (err error) { + b := target.SetAutoAttach(autoAttach, waitForDebuggerOnStart) + if flatten != nil { + b = b.WithFlatten(*flatten) + } + if windowOpen != nil { + b = b.WithWindowOpen(*windowOpen) + } + return b.Do(doTarget.ctxWithExecutor) +} + +// SetDiscoverTargets controls whether to discover available targets and +// notify via targetCreated/targetInfoChanged/targetDestroyed events. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-setDiscoverTargets +// +// parameters: +// - `discover`: Whether to discover available targets. +func (doTarget Target) SetDiscoverTargets(discover bool) (err error) { + b := target.SetDiscoverTargets(discover) + return b.Do(doTarget.ctxWithExecutor) +} + +// SetRemoteLocations enables target discovery for the specified locations, +// when setDiscoverTargets was set to true. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Target#method-setRemoteLocations +// +// parameters: +// - `locations`: List of remote locations. +func (doTarget Target) SetRemoteLocations(locations []*target.RemoteLocation) (err error) { + b := target.SetRemoteLocations(locations) + return b.Do(doTarget.ctxWithExecutor) +} diff --git a/domain/tethering.go b/domain/tethering.go new file mode 100644 index 0000000..4ec95b3 --- /dev/null +++ b/domain/tethering.go @@ -0,0 +1,36 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/tethering" +) + +// Tethering executes a cdproto command under Tethering domain. +type Tethering struct { + ctxWithExecutor context.Context +} + +// Bind request browser port binding. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tethering#method-bind +// +// parameters: +// - `port`: Port number to bind. +func (doTethering Tethering) Bind(port int64) (err error) { + b := tethering.Bind(port) + return b.Do(doTethering.ctxWithExecutor) +} + +// Unbind request browser port unbinding. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tethering#method-unbind +// +// parameters: +// - `port`: Port number to unbind. +func (doTethering Tethering) Unbind(port int64) (err error) { + b := tethering.Unbind(port) + return b.Do(doTethering.ctxWithExecutor) +} diff --git a/domain/tracing.go b/domain/tracing.go new file mode 100644 index 0000000..8251375 --- /dev/null +++ b/domain/tracing.go @@ -0,0 +1,92 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/tracing" +) + +// Tracing executes a cdproto command under Tracing domain. +type Tracing struct { + ctxWithExecutor context.Context +} + +// End stop trace events collection. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-end +func (doTracing Tracing) End() (err error) { + b := tracing.End() + return b.Do(doTracing.ctxWithExecutor) +} + +// GetCategories gets supported tracing categories. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-getCategories +// +// returns: +// - `retCategories`: A list of supported tracing categories. +func (doTracing Tracing) GetCategories() (retCategories []string, err error) { + b := tracing.GetCategories() + return b.Do(doTracing.ctxWithExecutor) +} + +// RecordClockSyncMarker record a clock sync marker in the trace. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-recordClockSyncMarker +// +// parameters: +// - `syncID`: The ID of this clock sync marker +func (doTracing Tracing) RecordClockSyncMarker(syncID string) (err error) { + b := tracing.RecordClockSyncMarker(syncID) + return b.Do(doTracing.ctxWithExecutor) +} + +// RequestMemoryDump request a global memory dump. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-requestMemoryDump +// +// parameters: +// - `deterministic`: This can be nil. (Optional) Enables more deterministic results by forcing garbage collection +// +// returns: +// - `retDumpGUID`: GUID of the resulting global memory dump. +// - `retSuccess`: True iff the global memory dump succeeded. +func (doTracing Tracing) RequestMemoryDump(deterministic *bool) (retDumpGUID string, retSuccess bool, err error) { + b := tracing.RequestMemoryDump() + if deterministic != nil { + b = b.WithDeterministic(*deterministic) + } + return b.Do(doTracing.ctxWithExecutor) +} + +// Start start trace events collection. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/Tracing#method-start +// +// parameters: +// - `bufferUsageReportingInterval`: This can be nil. (Optional) If set, the agent will issue bufferUsage events at this interval, specified in milliseconds +// - `transferMode`: This can be nil. (Optional) Whether to report trace events as series of dataCollected events or to save trace to a stream (defaults to ReportEvents). +// - `streamFormat`: This can be nil. (Optional) Trace data format to use. This only applies when using ReturnAsStream transfer mode (defaults to json). +// - `streamCompression`: This can be nil. (Optional) Compression format to use. This only applies when using ReturnAsStream transfer mode (defaults to none) +// - `traceConfig` +func (doTracing Tracing) Start(bufferUsageReportingInterval *float64, transferMode *tracing.TransferMode, streamFormat *tracing.StreamFormat, streamCompression *tracing.StreamCompression, traceConfig *tracing.TraceConfig) (err error) { + b := tracing.Start() + if bufferUsageReportingInterval != nil { + b = b.WithBufferUsageReportingInterval(*bufferUsageReportingInterval) + } + if transferMode != nil { + b = b.WithTransferMode(*transferMode) + } + if streamFormat != nil { + b = b.WithStreamFormat(*streamFormat) + } + if streamCompression != nil { + b = b.WithStreamCompression(*streamCompression) + } + if traceConfig != nil { + b = b.WithTraceConfig(traceConfig) + } + return b.Do(doTracing.ctxWithExecutor) +} diff --git a/domain/webaudio.go b/domain/webaudio.go new file mode 100644 index 0000000..488165b --- /dev/null +++ b/domain/webaudio.go @@ -0,0 +1,45 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/webaudio" +) + +// WebAudio executes a cdproto command under WebAudio domain. +type WebAudio struct { + ctxWithExecutor context.Context +} + +// Enable enables the WebAudio domain and starts sending context lifetime +// events. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#method-enable +func (doWebAudio WebAudio) Enable() (err error) { + b := webaudio.Enable() + return b.Do(doWebAudio.ctxWithExecutor) +} + +// Disable disables the WebAudio domain. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#method-disable +func (doWebAudio WebAudio) Disable() (err error) { + b := webaudio.Disable() + return b.Do(doWebAudio.ctxWithExecutor) +} + +// GetRealtimeData fetch the realtime data from the registered contexts. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAudio#method-getRealtimeData +// +// parameters: +// - `contextID` +// +// returns: +// - `retRealtimeData` +func (doWebAudio WebAudio) GetRealtimeData(contextID webaudio.GraphObjectID) (retRealtimeData *webaudio.ContextRealtimeData, err error) { + b := webaudio.GetRealtimeData(contextID) + return b.Do(doWebAudio.ctxWithExecutor) +} diff --git a/domain/webauthn.go b/domain/webauthn.go new file mode 100644 index 0000000..71adccb --- /dev/null +++ b/domain/webauthn.go @@ -0,0 +1,135 @@ +package domain + +// Code generated by chromebot-domain-gen. DO NOT EDIT. + +import ( + "context" + + "github.com/chromedp/cdproto/webauthn" +) + +// WebAuthn executes a cdproto command under WebAuthn domain. +type WebAuthn struct { + ctxWithExecutor context.Context +} + +// Enable enable the WebAuthn domain and start intercepting credential +// storage and retrieval with a virtual authenticator. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-enable +func (doWebAuthn WebAuthn) Enable() (err error) { + b := webauthn.Enable() + return b.Do(doWebAuthn.ctxWithExecutor) +} + +// Disable disable the WebAuthn domain. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-disable +func (doWebAuthn WebAuthn) Disable() (err error) { + b := webauthn.Disable() + return b.Do(doWebAuthn.ctxWithExecutor) +} + +// AddVirtualAuthenticator creates and adds a virtual authenticator. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-addVirtualAuthenticator +// +// parameters: +// - `options` +// +// returns: +// - `retAuthenticatorID` +func (doWebAuthn WebAuthn) AddVirtualAuthenticator(options *webauthn.VirtualAuthenticatorOptions) (retAuthenticatorID webauthn.AuthenticatorID, err error) { + b := webauthn.AddVirtualAuthenticator(options) + return b.Do(doWebAuthn.ctxWithExecutor) +} + +// RemoveVirtualAuthenticator removes the given authenticator. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-removeVirtualAuthenticator +// +// parameters: +// - `authenticatorID` +func (doWebAuthn WebAuthn) RemoveVirtualAuthenticator(authenticatorID webauthn.AuthenticatorID) (err error) { + b := webauthn.RemoveVirtualAuthenticator(authenticatorID) + return b.Do(doWebAuthn.ctxWithExecutor) +} + +// AddCredential adds the credential to the specified authenticator. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-addCredential +// +// parameters: +// - `authenticatorID` +// - `credential` +func (doWebAuthn WebAuthn) AddCredential(authenticatorID webauthn.AuthenticatorID, credential *webauthn.Credential) (err error) { + b := webauthn.AddCredential(authenticatorID, credential) + return b.Do(doWebAuthn.ctxWithExecutor) +} + +// GetCredential returns a single credential stored in the given virtual +// authenticator that matches the credential ID. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-getCredential +// +// parameters: +// - `authenticatorID` +// - `credentialID` +// +// returns: +// - `retCredential` +func (doWebAuthn WebAuthn) GetCredential(authenticatorID webauthn.AuthenticatorID, credentialID string) (retCredential *webauthn.Credential, err error) { + b := webauthn.GetCredential(authenticatorID, credentialID) + return b.Do(doWebAuthn.ctxWithExecutor) +} + +// GetCredentials returns all the credentials stored in the given virtual +// authenticator. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-getCredentials +// +// parameters: +// - `authenticatorID` +// +// returns: +// - `retCredentials` +func (doWebAuthn WebAuthn) GetCredentials(authenticatorID webauthn.AuthenticatorID) (retCredentials []*webauthn.Credential, err error) { + b := webauthn.GetCredentials(authenticatorID) + return b.Do(doWebAuthn.ctxWithExecutor) +} + +// RemoveCredential removes a credential from the authenticator. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-removeCredential +// +// parameters: +// - `authenticatorID` +// - `credentialID` +func (doWebAuthn WebAuthn) RemoveCredential(authenticatorID webauthn.AuthenticatorID, credentialID string) (err error) { + b := webauthn.RemoveCredential(authenticatorID, credentialID) + return b.Do(doWebAuthn.ctxWithExecutor) +} + +// ClearCredentials clears all the credentials from the specified device. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-clearCredentials +// +// parameters: +// - `authenticatorID` +func (doWebAuthn WebAuthn) ClearCredentials(authenticatorID webauthn.AuthenticatorID) (err error) { + b := webauthn.ClearCredentials(authenticatorID) + return b.Do(doWebAuthn.ctxWithExecutor) +} + +// SetUserVerified sets whether User Verification succeeds or fails for an +// authenticator. The default is true. +// +// See: https://chromedevtools.github.io/devtools-protocol/tot/WebAuthn#method-setUserVerified +// +// parameters: +// - `authenticatorID` +// - `isUserVerified` +func (doWebAuthn WebAuthn) SetUserVerified(authenticatorID webauthn.AuthenticatorID, isUserVerified bool) (err error) { + b := webauthn.SetUserVerified(authenticatorID, isUserVerified) + return b.Do(doWebAuthn.ctxWithExecutor) +} diff --git a/example_test.go b/example_test.go new file mode 100644 index 0000000..b0e425d --- /dev/null +++ b/example_test.go @@ -0,0 +1,68 @@ +package chromebot_test + +import ( + "fmt" + "testing" + + "github.com/chromedp/chromedp" + "github.com/nanitefactory/chromebot" +) + +func ExampleNew() { + // Start a browser + browser := chromebot.New(false) + defer browser.Close() + + // Navigate + browser.Tab(0).Run( + chromedp.Navigate("https://godoc.org"), + chromedp.WaitVisible("html"), + ) + + // Another navigation method + // browser.Tab(0).Do().Page().Navigate("https://godoc.org", nil, nil, nil) + + // Get cookies + cookies, err := browser.Tab(0).Do().Network().GetAllCookies() + if err != nil { + panic(err) + } + + // Print + for i, cookie := range cookies { + fmt.Println(i, cookie) + } + + // _Output: + // 0 &{__utma 58978491.1884756898.1576137201.1576137201.1576137201.1 .godoc.org / 1.639209201e+09 60 false false false } + // 1 &{__utmc 58978491 .godoc.org / -1 14 false false true } + // 2 &{__utmz 58978491.1576137201.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none) .godoc.org / 1.591905201e+09 75 false false false } + // 3 &{__utmt 1 .godoc.org / 1.576137801e+09 7 false false false } + // 4 &{__utmb 58978491.1.10.1576137201 .godoc.org / 1.576139001e+09 30 false false false } +} + +func TestExampleNew(t *testing.T) { + // Start a browser + browser := chromebot.New(false) + defer browser.Close() + // Navigate + if err := browser.Tab(0).Run( + chromedp.Navigate("https://godoc.org"), + chromedp.WaitVisible("html"), + ); err != nil { + panic(err) + } + // Another navigation method + if _, _, strErr, err := browser.Tab(0).Do().Page().Navigate("https://godoc.org", nil, nil, nil); err != nil { + panic(fmt.Sprint(err, strErr)) + } + // Get cookies + cookies, err := browser.Tab(0).Do().Network().GetAllCookies() + if err != nil { + panic(err) + } + // Print + for i, cookie := range cookies { + t.Log(i, cookie) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..21077e4 --- /dev/null +++ b/go.mod @@ -0,0 +1,9 @@ +module github.com/nanitefactory/chromebot + +go 1.12 + +require ( + github.com/chromedp/cdproto v0.0.0-20191114225735-6626966fbae4 + github.com/chromedp/chromedp v0.5.2 + github.com/mailru/easyjson v0.7.0 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..25ef035 --- /dev/null +++ b/go.sum @@ -0,0 +1,16 @@ +github.com/chromedp/cdproto v0.0.0-20191114225735-6626966fbae4 h1:QD3KxSJ59L2lxG6MXBjNHxiQO2RmxTQ3XcK+wO44WOg= +github.com/chromedp/cdproto v0.0.0-20191114225735-6626966fbae4/go.mod h1:PfAWWKJqjlGFYJEidUM6aVIWPr0EpobeyVWEEmplX7g= +github.com/chromedp/chromedp v0.5.2 h1:W8xBXQuUnd2dZK0SN/lyVwsQM7KgW+kY5HGnntms194= +github.com/chromedp/chromedp v0.5.2/go.mod h1:rsTo/xRo23KZZwFmWk2Ui79rBaVRRATCjLzNQlOFSiA= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee h1:s+21KNqlpePfkah2I+gwHF8xmJWRjooY+5248k6m4A0= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= +github.com/gobwas/pool v0.2.0 h1:QEmUOlnSjWtnpRGHF3SauEiOsy82Cup83Vf2LcMlnc8= +github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.0.2 h1:CoAavW/wd/kulfZmSIBt6p24n4j7tHgNVCjsfHVNUbo= +github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= +github.com/knq/sysutil v0.0.0-20191005231841-15668db23d08 h1:V0an7KRw92wmJysvFvtqtKMAPmvS5O0jtB0nYo6t+gs= +github.com/knq/sysutil v0.0.0-20191005231841-15668db23d08/go.mod h1:dFWs1zEqDjFtnBXsd1vPOZaLsESovai349994nHx3e0= +github.com/mailru/easyjson v0.7.0 h1:aizVhC/NAAcKWb+5QsU1iNOZb4Yws5UO2I+aIprQITM= +github.com/mailru/easyjson v0.7.0/go.mod h1:KAzv3t3aY1NaHWoQz1+4F1ccyAH66Jk7yos7ldAVICs= +golang.org/x/sys v0.0.0-20191113165036-4c7a9d0fe056 h1:dHtDnRWQtSx0Hjq9kvKFpBh9uPPKfQN70NZZmvssGwk= +golang.org/x/sys v0.0.0-20191113165036-4c7a9d0fe056/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/tab.go b/tab.go new file mode 100644 index 0000000..5fa85cf --- /dev/null +++ b/tab.go @@ -0,0 +1,117 @@ +package chromebot + +import ( + "context" + "errors" + "sync" + + "github.com/chromedp/cdproto/cdp" + "github.com/chromedp/chromedp" + "github.com/nanitefactory/chromebot/domain" +) + +// Tab represents a running tab. +type Tab struct { + finMu sync.Mutex + fin chan struct{} + ctx context.Context + cancel context.CancelFunc + closeStrategy func(ctx context.Context) // inject close method other than cancel() +} + +func newTab(ctx context.Context, cancel context.CancelFunc, closeStrategy func(ctx context.Context)) *Tab { + if closeStrategy == nil { + closeStrategy = func(ctx context.Context) { cancel() } + } + ret := &Tab{ + finMu: sync.Mutex{}, + fin: make(chan struct{}), + ctx: ctx, + cancel: cancel, + closeStrategy: closeStrategy, + } + go func() { + <-ctx.Done() + defer func() { // DCL + ret.finMu.Lock() + defer ret.finMu.Unlock() + select { + case <-ret.fin: + return + default: + close(ret.fin) + } + }() + }() + return ret +} + +func newMainTab(ctx context.Context, cancel context.CancelFunc) *Tab { + return newTab(ctx, cancel, func(ctx context.Context) { + domain.Do(cdp.WithExecutor(ctx, chromedp.FromContext(ctx).Target)).Page().Close() + }) +} + +func newExtraTab(ctx context.Context, cancel context.CancelFunc) *Tab { + return newTab(ctx, cancel, nil) +} + +// Close closes this tab. +func (t *Tab) Close() { + defer func() { // DCL + t.finMu.Lock() + defer t.finMu.Unlock() + select { + case <-t.fin: + return + default: + t.closeStrategy(t.ctx) + close(t.fin) + } + }() +} + +// Dead returns a channel that's closed when work done on behalf of the tab should be dead. +// This notifies a user if and only if the browser is dead or `(*Tab).Close()` has been called. +func (t *Tab) Dead() <-chan struct{} { + return t.fin +} + +// Do runs a cdproto command on this tab. +func (t *Tab) Do() domain.Domain { + return domain.Do(cdp.WithExecutor(t.ctx, chromedp.FromContext(t.ctx).Target)) +} + +// Run runs a chromedp action on this tab. +func (t *Tab) Run(actions ...chromedp.Action) error { + return chromedp.Run(t.ctx, actions...) +} + +// Listen adds a callback function which will be called whenever an event is received on this tab. +// +// Usage: +// t.Listen(func(ev interface{}) { +// switch ev := ev.(type) { +// case *page.EventJavascriptDialogOpening: +// // do something with ev +// case *runtime.EventConsoleAPICalled: +// // do something with ev +// case *runtime.EventExceptionThrown: +// // do something with ev +// } +// }) +// +// Note that the function is called synchronously when handling events. +// The function should avoid blocking at all costs. +// For example, any Actions must be run via a separate goroutine. +func (t *Tab) Listen(fn func(ev interface{})) error { + select { + case <-t.ctx.Done(): + return errors.New("tab closed: " + t.ctx.Err().Error()) + case <-t.fin: + return errors.New("tab closed") + default: + } + chromedp.ListenTarget(t.ctx, fn) + return nil +} diff --git a/tab_test.go b/tab_test.go new file mode 100644 index 0000000..4fccba2 --- /dev/null +++ b/tab_test.go @@ -0,0 +1,63 @@ +package chromebot_test + +import ( + "fmt" + "sync" + "testing" + + "github.com/chromedp/chromedp" + "github.com/nanitefactory/chromebot" +) + +func TestTab(t *testing.T) { + c := chromebot.New(false) + defer c.Close() + c.AddNewTab() + // + wg := sync.WaitGroup{} + doRunTest := func(iTab int) { + defer wg.Add(-1) + // Navigate + if err := c.Tab(iTab).Run( + chromedp.Navigate("https://godoc.org"), + chromedp.WaitVisible("html"), + ); err != nil { + panic(err) + } + // Another navigation method + if _, _, strErr, err := c.Tab(iTab).Do().Page().Navigate("https://godoc.org", nil, nil, nil); err != nil { + panic(fmt.Sprint(err, strErr)) + } + // Get cookies + cookies, err := c.Tab(iTab).Do().Network().GetAllCookies() + if err != nil { + panic(err) + } + // Print + for i, cookie := range cookies { + t.Log(i, cookie) + } + } + c.Tab(0).Listen(func(interface{}) {}) + c.Tab(1).Listen(func(interface{}) {}) + wg.Add(2) + go doRunTest(0) + go doRunTest(1) + wg.Wait() + c.Tab(0).Close() + c.Tab(1).Close() + for i := 0; i < 10; i++ { + select { + case <-c.Tab(0).Dead(): + default: + panic("Dead() not working well") + } + } + for i := 0; i < 10; i++ { + select { + case <-c.Tab(1).Dead(): + default: + panic("Dead() not working well") + } + } +}