How to use Connect method of cdp Package

Best Rod code snippet using cdp.Connect

tab.go

Source:tab.go Github

copy

Full Screen

1package chrome2import (3 "context"4 "encoding/base64"5 "fmt"6 "github.com/mafredri/cdp"7 "github.com/mafredri/cdp/protocol/dom"8 "github.com/mafredri/cdp/protocol/emulation"9 "github.com/mafredri/cdp/protocol/page"10 "github.com/mafredri/cdp/protocol/runtime"11 "github.com/mafredri/cdp/protocol/target"12 "github.com/mafredri/cdp/rpcc"13 "log"14 "time"15)16type Tab interface {17 Navigate(url string, timeout time.Duration) (bool, error)18 GetHTML(timeout time.Duration) (string, error)19 CaptureScreenshot(opts ScreenshotOpts, timeout time.Duration) (string, error)20 Exec(javascript string, timeout time.Duration) (*runtime.EvaluateReply, error)21 GetClient() *cdp.Client22 GetTargetID() target.ID23 AttachHook(hook ClientHook)24}25type ClientHook func(c *cdp.Client) error26type ClientHooks []ClientHook27type tab struct {28 // target id of a single tab29 id target.ID30 // port on which chrome process is listening for dev tools protocol31 port *int32 // connection to connect with the browser33 conn *rpcc.Conn34 // client to control the browser35 client *cdp.Client36 // hooks to attach additional functionality to client, enable domains etc37 hooks ClientHooks38}39func (t *tab) connect(timeout time.Duration) error {40 ctx, cancel := context.WithTimeout(context.Background(), timeout)41 defer cancel()42 var err error43 // connect to chrome44 t.conn, err = rpcc.DialContext(45 ctx,46 fmt.Sprintf("ws://127.0.0.1:%v/devtools/page/%v", IntValue(t.port), t.id),47 )48 if err != nil {49 log.Println("go-chrome-framework error: unable to connect to target", err.Error())50 return err51 }52 // This cdp Client controls the tab.53 t.client = cdp.NewClient(t.conn)54 // execute hooks for current target55 for _, hook := range t.hooks {56 err := hook(t.client)57 if err != nil {58 log.Println("go-chrome-framework error: unable to execute hook", err.Error())59 return err60 }61 }62 return nil63}64func (t *tab) disconnect() error {65 return t.conn.Close()66}67func (t *tab) Navigate(url string, timeout time.Duration) (bool, error) {68 ctx, cancel := context.WithTimeout(context.Background(), timeout)69 defer cancel()70 if t.conn == nil {71 err := t.connect(timeout)72 if err != nil {73 return false, err74 }75 }76 // Open a DOMContentEventFired Client to buffer this event.77 domContent, err := t.client.Page.DOMContentEventFired(ctx)78 if err != nil {79 log.Println("go-chrome-framework error: unable to open dom content event fired client", err.Error())80 return false, err81 }82 defer closeRes(domContent)83 // Enable events on the Page domain, it's often preferable to create84 // event clients before enabling events so that we don't miss any.85 if err = t.client.Page.Enable(ctx); err != nil {86 log.Println("go-chrome-framework error: unable to enable page domain", err.Error())87 return false, err88 }89 // Create the Navigate arguments with the optional Referrer field set.90 navArgs := page.NewNavigateArgs(url)91 nav, err := t.client.Page.Navigate(ctx, navArgs)92 if err != nil {93 log.Println("go-chrome-framework error: unable to navigate to given url", err.Error())94 return false, err95 }96 // Wait until we have a DOMContentEventFired event.97 _, err = domContent.Recv()98 if err != nil {99 log.Println("go-chrome-framework error: unable to get dom content event", err.Error())100 return false, err101 }102 log.Printf("go-chrome-framework: page loaded with frame ID: %s\n", nav.FrameID)103 return true, nil104}105func (t *tab) GetHTML(timeout time.Duration) (string, error) {106 ctx, cancel := context.WithTimeout(context.Background(), timeout)107 defer cancel()108 if t.conn == nil {109 err := t.connect(timeout)110 if err != nil {111 return "", err112 }113 }114 // Fetch the document root node. We can pass nil here115 // since this method only takes optional arguments.116 doc, err := t.client.DOM.GetDocument(ctx, nil)117 if err != nil {118 log.Println("go-chrome-framework error: unable to get DOM root node", err.Error())119 return "", err120 }121 // Get the outer HTML for the page.122 result, err := t.client.DOM.GetOuterHTML(ctx, &dom.GetOuterHTMLArgs{123 NodeID: &doc.Root.NodeID,124 })125 if err != nil {126 log.Println("go-chrome-framework error: unable to get outer html", err.Error())127 return "", err128 }129 return result.OuterHTML, nil130}131func (t *tab) CaptureScreenshot(opts ScreenshotOpts, timeout time.Duration) (string, error) {132 ctx, cancel := context.WithTimeout(context.Background(), timeout)133 defer cancel()134 if t.conn == nil {135 err := t.connect(timeout)136 if err != nil {137 return "", err138 }139 }140 // Fetch the document root node. We can pass nil here141 // since this method only takes optional arguments.142 doc, err := t.client.DOM.GetDocument(ctx, nil)143 if err != nil {144 log.Println("go-chrome-framework error: unable to get DOM root node", err.Error())145 return "", err146 }147 querySelectorArgs := dom.NewQuerySelectorArgs(doc.Root.NodeID, "body")148 bodyNode, err := t.client.DOM.QuerySelector(ctx, querySelectorArgs)149 if err != nil {150 log.Println("go-chrome-framework error: unable to get DOM root node", err.Error())151 return "", err152 }153 getBoxModelArgs := dom.NewGetBoxModelArgs().SetNodeID(bodyNode.NodeID)154 bodyBoxModel, err := t.client.DOM.GetBoxModel(ctx, getBoxModelArgs)155 if err != nil {156 log.Println("go-chrome-framework error: unable to get DOM root node", err.Error())157 return "", err158 }159 if opts.Width == 0 {160 opts.Width = 800161 }162 if opts.Height == 0 {163 opts.Height = bodyBoxModel.Model.Height164 }165 if opts.DeviceScaleFactor == 0 {166 opts.DeviceScaleFactor = 1.0167 }168 deviceMetricsOverrideArgs := emulation.NewSetDeviceMetricsOverrideArgs(opts.Width, opts.Height, opts.DeviceScaleFactor, opts.Mobile)169 err = t.client.Emulation.SetDeviceMetricsOverride(ctx, deviceMetricsOverrideArgs)170 screenshotArgs := page.NewCaptureScreenshotArgs().SetFormat("png").SetQuality(80)171 screenshot, err := t.client.Page.CaptureScreenshot(ctx, screenshotArgs)172 if err != nil {173 // error174 return "", err175 }176 image := fmt.Sprintf("data:image/png;base64,%v", base64.StdEncoding.EncodeToString(screenshot.Data))177 return image, nil178}179func (t *tab) Exec(javascript string, timeout time.Duration) (*runtime.EvaluateReply, error) {180 ctx, cancel := context.WithTimeout(context.Background(), timeout)181 defer cancel()182 if t.conn == nil {183 err := t.connect(timeout)184 if err != nil {185 return nil, err186 }187 }188 evalArgs := runtime.NewEvaluateArgs(javascript).SetAwaitPromise(true).SetReturnByValue(true)189 return t.client.Runtime.Evaluate(ctx, evalArgs)190}191func (t *tab) GetClient() *cdp.Client {192 if t.client == nil {193 err := t.connect(120 * time.Second)194 if err != nil {195 log.Println("unable to connect", err)196 return nil197 }198 }199 return t.client200}201func (t *tab) GetTargetID() target.ID {202 return t.id203}204func (t *tab) AttachHook(hook ClientHook) {205 t.hooks = append(t.hooks, hook)206}...

Full Screen

Full Screen

websocket_test.go

Source:websocket_test.go Github

copy

Full Screen

...51 g.Eq(r.URL.Query().Get("q"), "ok")52 close(wait)53 })54 ws := cdp.WebSocket{}55 err := ws.Connect(g.Context(), s.URL("/a?q=ok"), http.Header{56 "Host": {"test.com"},57 "Test": {"header"},58 })59 <-wait60 g.Eq(err.Error(), "websocket bad handshake: 200 OK. ")61}62func newPage(ctx context.Context, g got.G) (*cdp.Client, string) {63 l := launcher.New()64 g.Cleanup(l.Kill)65 client := cdp.New().Start(cdp.MustConnectWS(l.MustLaunch()))66 go func() {67 for range client.Event() {68 }69 }()70 file, err := filepath.Abs(filepath.FromSlash("fixtures/basic.html"))71 g.E(err)72 res, err := client.Call(ctx, "", "Target.createTarget", map[string]interface{}{73 "url": "file://" + file,74 })75 g.E(err)76 targetID := gson.New(res).Get("targetId").String()77 res, err = client.Call(ctx, "", "Target.attachToTarget", map[string]interface{}{78 "targetId": targetID,79 "flatten": true,80 })81 g.E(err)82 sessionID := gson.New(res).Get("sessionId").String()83 return client, sessionID84}85func TestDuplicatedConnectErr(t *testing.T) {86 g := setup(t)87 l := launcher.New()88 g.Cleanup(l.Kill)89 u := l.MustLaunch()90 ws := &cdp.WebSocket{}91 g.E(ws.Connect(g.Context(), u, nil))92 g.Panic(func() {93 _ = ws.Connect(g.Context(), u, nil)94 })95}...

Full Screen

Full Screen

example_test.go

Source:example_test.go Github

copy

Full Screen

...12 ctx := context.Background()13 // launch a browser14 url := launcher.New().MustLaunch()15 // create a controller16 client := cdp.New().Start(cdp.MustConnectWS(url))17 go func() {18 for range client.Event() {19 // you must consume the events20 }21 }()22 // Such as call this endpoint on the api doc:23 // https://chromedevtools.github.io/devtools-protocol/tot/Page#method-navigate24 // This will create a new tab and navigate to the test.com25 res, err := client.Call(ctx, "", "Target.createTarget", map[string]string{26 "url": "http://test.com",27 })28 utils.E(err)29 fmt.Println(len(gson.New(res).Get("targetId").Str()))30 // close browser by using the proto lib to encode json31 _ = proto.BrowserClose{}.Call(client)32 // Output: 3233}34func Example_customize_cdp_log() {35 ws := cdp.MustConnectWS(launcher.New().MustLaunch())36 cdp.New().37 Logger(utils.Log(func(args ...interface{}) {38 switch v := args[0].(type) {39 case *cdp.Request:40 fmt.Printf("id: %d", v.ID)41 }42 })).43 Start(ws)44}...

Full Screen

Full Screen

Connect

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx, cancel := chromedp.NewContext(4 context.Background(),5 chromedp.WithLogf(log.Printf),6 defer cancel()7 err := chromedp.Run(ctx, chromedp.Tasks{8 chromedp.WaitVisible(`#searchform`, chromedp.ByID),9 chromedp.Value(`#lst-ib`, &res, chromedp.ByID),10 })11 if err != nil {12 log.Fatal(err)13 }14 fmt.Printf("Search box value: %s15}16import (17func main() {18 ctx, cancel := chromedp.NewContext(context.Background())19 defer cancel()20 err := chromedp.Run(ctx, chromedp.Tasks{21 chromedp.WaitVisible(`#searchform`, chromedp.ByID),22 chromedp.Value(`#lst-ib`, &res, chromedp.ByID),23 })24 if err != nil {25 log.Fatal(err)26 }27 fmt.Printf("Search box value: %s28}29import (30func main() {31 ctx, cancel := chromedp.NewContext(context.Background())32 defer cancel()33 err := chromedp.Run(ctx, chromedp.Tasks{34 chromedp.WaitVisible(`#searchform`, chromedp.ByID),35 chromedp.Value(`#lst-ib`, &res, chromedp.ByID),36 })37 if err != nil {38 log.Fatal(err

Full Screen

Full Screen

Connect

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx, cancel := chromedp.NewContext(4 defer cancel()5 err := chromedp.Run(ctx,6 chromedp.WaitVisible(`#hplogo`),7 chromedp.Click(`#hplogo`),8 chromedp.OuterHTML(`#hplogo`, &res),9 if err != nil {10 log.Fatal(err)11 }12 fmt.Println(res)13}14import (15func main() {16 ctx, cancel := chromedp.NewContext(17 defer cancel()18 err := chromedp.Run(ctx,19 chromedp.WaitVisible(`#hplogo`),20 chromedp.Click(`#hplogo`),21 chromedp.OuterHTML(`#hplogo`, &res),22 if err != nil {23 log.Fatal(err)24 }25 fmt.Println(res)26}27import (28func main() {29 ctx, cancel := chromedp.NewContext(30 defer cancel()31 err := chromedp.Run(ctx,32 chromedp.WaitVisible(`#hplogo`),33 chromedp.Click(`#hplogo`),34 chromedp.OuterHTML(`#hplogo`, &res),35 if err != nil {36 log.Fatal(err)37 }38 fmt.Println(res)39}

Full Screen

Full Screen

Connect

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 c := cdp.New()4 if err != nil {5 fmt.Println(err)6 }7 c.Close()8}9import (10func main() {11 c := cdp.New()

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful