Skip to content

Commit

Permalink
add an example about reusing a browser
Browse files Browse the repository at this point in the history
Use javascript with cookies, which is a pretty common way to "save" work
between separate visits to the same site in the same browser.

This also shows how to use timeouts properly, without having the timeout
affect the entire browser's process.

Fixes chromedp#548.
  • Loading branch information
mvdan committed Jan 6, 2020
1 parent aa5cc87 commit ff70bc3
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
47 changes: 47 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"os"
"path/filepath"
"strings"
"time"

"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/dom"
Expand Down Expand Up @@ -92,6 +93,52 @@ func ExampleExecAllocator() {
// DevToolsActivePort has 2 lines
}

func ExampleNewContext_reuseBrowser() {
ts := httptest.NewServer(writeHTML(`
<body>
<script>
// Show the current cookies.
var p = document.createElement("p")
p.innerText = document.cookie
p.setAttribute("id", "cookies")
document.body.appendChild(p)
// Override the cookies.
document.cookie = "foo=bar"
</script>
</body>
`))
defer ts.Close()

// create a new browser
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()

// start the browser without a timeout
if err := chromedp.Run(ctx); err != nil {
panic(err)
}

for i := 0; i < 2; i++ {
// look at the page twice, with a timeout set up; we skip
// cancels for the sake of brevity
ctx, _ := context.WithTimeout(ctx, time.Second)
ctx, _ = chromedp.NewContext(ctx)
var cookies string
if err := chromedp.Run(ctx,
chromedp.Navigate(ts.URL),
chromedp.Text("#cookies", &cookies),
); err != nil {
panic(err)
}
fmt.Printf("Cookies at i=%d: %q\n", i, cookies)
}

// Output:
// Cookies at i=0: ""
// Cookies at i=1: "foo=bar"
}

func ExampleNewContext_manyTabs() {
// new browser, first tab
ctx1, cancel := chromedp.NewContext(context.Background())
Expand Down
2 changes: 1 addition & 1 deletion util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const dumpJS = `(function dump(n, prefix, indent, nodeIDs) {
var s = '';
if (typeof n.localName !== 'undefined') {
s = n.localName;
}
}
if (s === '' && typeof n.nodeName !== 'undefined') {
s = n.nodeName;
}
Expand Down

0 comments on commit ff70bc3

Please sign in to comment.