Skip to content

Instantly share code, notes, and snippets.

@16892434
Forked from NaniteFactory/setcookie.go
Created October 13, 2022 03:03
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 16892434/82256b815e9fbc084bab97e460f719e1 to your computer and use it in GitHub Desktop.
Save 16892434/82256b815e9fbc084bab97e460f719e1 to your computer and use it in GitHub Desktop.
chromedp set-cookie example
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
)
func main() {
// create chrome instance
ctx, cancel := chromedp.NewContext(
context.Background(),
chromedp.WithLogf(log.Printf),
)
defer cancel()
// create a timeout
ctx, cancel = context.WithTimeout(ctx, 15*time.Second)
defer cancel()
// navigate to a page, wait for an element, click
var example string
err := chromedp.Run(ctx,
SetCookie("test", "vv", "golang.org", "/", false, false),
chromedp.Navigate(`https://golang.org/pkg/time/`),
chromedp.WaitVisible(`body > footer`), // wait for footer element is visible (ie, page is loaded)
chromedp.Click(`#pkg-examples > div`, chromedp.NodeVisible), // find and click "Expand All" link
chromedp.Value(`#example_After .play .input textarea`, &example), // retrieve the value of the textarea
ShowCookies(),
)
if err != nil {
log.Fatal(err)
}
log.Printf("Go's time.After example:\n%s", example)
}
func SetCookie(name, value, domain, path string, httpOnly, secure bool) chromedp.Action {
return chromedp.ActionFunc(func(ctx context.Context) error {
expr := cdp.TimeSinceEpoch(time.Now().Add(180 * 24 * time.Hour))
success, err := network.SetCookie(name, value).
WithExpires(&expr).
WithDomain(domain).
WithPath(path).
WithHTTPOnly(httpOnly).
WithSecure(secure).
Do(ctx)
if err != nil {
return err
}
if !success {
return fmt.Errorf("could not set cookie %s", name)
}
return nil
})
}
func ShowCookies() chromedp.Action {
return chromedp.ActionFunc(func(ctx context.Context) error {
cookies, err := network.GetAllCookies().Do(ctx)
if err != nil {
return err
}
for i, cookie := range cookies {
log.Printf("chrome cookie %d: %+v", i, cookie)
}
return nil
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment