Skip to content

Instantly share code, notes, and snippets.

@mafredri
Last active January 10, 2019 06:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mafredri/85296b6c4c24c3da2898e6fa3709e6aa to your computer and use it in GitHub Desktop.
Save mafredri/85296b6c4c24c3da2898e6fa3709e6aa to your computer and use it in GitHub Desktop.
// This example gives permission to access geolocation
// and fetches the current position via JavaScript.
// Tested on: cdp v0.18.7 and Chrome Canary 70.0.3532.0,
// and seems to work in both headless and headfull mode.
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/mafredri/cdp"
"github.com/mafredri/cdp/devtool"
"github.com/mafredri/cdp/protocol/browser"
"github.com/mafredri/cdp/protocol/emulation"
"github.com/mafredri/cdp/protocol/page"
"github.com/mafredri/cdp/protocol/runtime"
"github.com/mafredri/cdp/rpcc"
)
func main() {
err := run(15 * time.Second)
if err != nil {
log.Fatal(err)
}
}
func run(timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
devt := devtool.New("http://127.0.0.1:9222")
pt, err := devt.Get(ctx, devtool.Page)
if err != nil {
pt, err = devt.Create(ctx)
if err != nil {
return err
}
}
conn, err := rpcc.DialContext(ctx, pt.WebSocketDebuggerURL)
if err != nil {
return err
}
defer conn.Close()
c := cdp.NewClient(conn)
domContent, err := c.Page.DOMContentEventFired(ctx)
if err != nil {
return err
}
defer domContent.Close()
if err = c.Page.Enable(ctx); err != nil {
return err
}
overrideArgs := emulation.NewSetGeolocationOverrideArgs().
SetLatitude(10).
SetLongitude(22).
SetAccuracy(100)
err = c.Emulation.SetGeolocationOverride(ctx, overrideArgs)
if err != nil {
return err
}
navArgs := page.NewNavigateArgs("https://www.google.com")
nav, err := c.Page.Navigate(ctx, navArgs)
if err != nil {
return err
}
if _, err = domContent.Recv(); err != nil {
return err
}
fmt.Printf("Page loaded with frame ID: %s\n", nav.FrameID)
err = c.Browser.GrantPermissions(ctx,
browser.NewGrantPermissionsArgs("https://www.google.com", []browser.PermissionType{
browser.PermissionTypeGeolocation,
}),
)
if err != nil {
return err
}
eval, err := c.Runtime.Evaluate(ctx, runtime.NewEvaluateArgs(`
new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
(pos) => {
// The protocol won't return this object straight, so we clone it.
const {latitude, longitude, accuracy} = pos.coords;
resolve({latitude, longitude, accuracy});
},
reject,
{timeout: 10000}
);
});
`).
SetAwaitPromise(true).
SetReturnByValue(true),
)
if err != nil {
return err
}
if eval.ExceptionDetails != nil {
return eval.ExceptionDetails
}
fmt.Println(eval.Result.String())
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment