Skip to content

Instantly share code, notes, and snippets.

@djmally
Created November 15, 2017 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djmally/188920c994feeaff9fd45f296e31b7d2 to your computer and use it in GitHub Desktop.
Save djmally/188920c994feeaff9fd45f296e31b7d2 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"github.com/mafredri/cdp"
"github.com/mafredri/cdp/devtool"
"github.com/mafredri/cdp/protocol/target"
"github.com/mafredri/cdp/rpcc"
)
func main() {
// Create a DevTools
dt := devtool.New(fmt.Sprintf("http://%s:%d", "localhost", 9222))
// Create a fresh Page target
_target, err := dt.Get(context.Background(), devtool.Page)
if err != nil {
// If there was no page context, create a new one
_target, err = dt.Create(context.Background())
if err != nil {
panic(err)
}
}
// Initiate a new RPC connection to the Chrome Debugging Protocol target.
conn, err := rpcc.DialContext(context.Background(), _target.WebSocketDebuggerURL, rpcc.WithWriteBufferSize(104857586))
if err != nil {
panic(err)
}
// Create a client
client := cdp.NewClient(conn)
// Should be 1 target, which has Attached = true
targets, err := client.Target.GetTargets(context.Background())
fmt.Println("---------------- INITIAL SET OF TARGETS ---------------------")
fmt.Printf("%+v %v\n", targets, err)
fmt.Println("")
origTarget := targets.TargetInfos[0]
client.Target.DetachFromTarget(context.Background(), target.NewDetachFromTargetArgs().SetTargetID(origTarget.TargetID))
// Should be 1 target, which we expect to have Attached = false, but will
// still be true even though we detached from it
fmt.Println("---------------- TARGETS AFTER DETACHING --------------------")
targets, err = client.Target.GetTargets(context.Background())
fmt.Printf("%+v %v\n", targets, err)
fmt.Println("")
createTargetReply, err := client.Target.CreateTarget(context.Background(), target.NewCreateTargetArgs("https://www.google.com"))
if err != nil {
panic(err)
}
// Should now be 2 targets, including the one whose ID is returned by CreateTarget
fmt.Println("---------------- TARGETS AFTER CREATING NEW TARGET ----------")
targets, err = client.Target.GetTargets(context.Background())
fmt.Printf("%+v %v\n", targets, err)
fmt.Printf("%+v\n", createTargetReply)
fmt.Println("")
err = client.Target.ActivateTarget(context.Background(), target.NewActivateTargetArgs(createTargetReply.TargetID))
if err != nil {
panic(err)
}
fmt.Println("---------------- TARGETS AFTER ACTIVATING THE CREATED TARGET --")
targets, err = client.Target.GetTargets(context.Background())
fmt.Printf("%+v %v\n", targets, err)
fmt.Println("")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment