From ff70bc3793cd6b2a45fec73fccc2391d5728b013 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Mart=C3=AD?= Date: Mon, 6 Jan 2020 13:59:28 +0900 Subject: [PATCH] add an example about reusing a browser 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 #548. --- example_test.go | 47 +++++++++++++++++++++++++++++++++++++++++++++++ util_test.go | 2 +- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/example_test.go b/example_test.go index ddbd6b74..c176b703 100644 --- a/example_test.go +++ b/example_test.go @@ -12,6 +12,7 @@ import ( "os" "path/filepath" "strings" + "time" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/dom" @@ -92,6 +93,52 @@ func ExampleExecAllocator() { // DevToolsActivePort has 2 lines } +func ExampleNewContext_reuseBrowser() { + ts := httptest.NewServer(writeHTML(` + + + + `)) + 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()) diff --git a/util_test.go b/util_test.go index 7bc8fe65..05d469e2 100644 --- a/util_test.go +++ b/util_test.go @@ -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; }