clarify NewContext's inheritance and cancellation

We have been developing this behavior over the past few weeks, but it
wasn't properly documented anywhere.

Fixes #303.
This commit is contained in:
Daniel Martí 2019-04-17 13:24:19 +09:00
parent e4c16681d0
commit 958088f83b
2 changed files with 14 additions and 4 deletions

View File

@ -23,8 +23,8 @@ type Allocator interface {
Allocate(context.Context, ...BrowserOption) (*Browser, error) Allocate(context.Context, ...BrowserOption) (*Browser, error)
// Wait blocks until an allocator has freed all of its resources. // Wait blocks until an allocator has freed all of its resources.
// Cancelling the context obtained via NewAllocator will already perform // Cancelling the allocator context will already perform this operation,
// this operation, so normally there's no need to call Wait directly. // so normally there's no need to call Wait directly.
Wait() Wait()
} }
@ -52,7 +52,7 @@ var DefaultExecAllocatorOptions = []ExecAllocatorOption{
} }
// NewExecAllocator creates a new context set up with an ExecAllocator, suitable // NewExecAllocator creates a new context set up with an ExecAllocator, suitable
// for use with NewContext or Run. // for use with NewContext.
func NewExecAllocator(parent context.Context, opts ...ExecAllocatorOption) (context.Context, context.CancelFunc) { func NewExecAllocator(parent context.Context, opts ...ExecAllocatorOption) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(parent) ctx, cancel := context.WithCancel(parent)
c := &Context{Allocator: setupExecAllocator(opts...)} c := &Context{Allocator: setupExecAllocator(opts...)}

View File

@ -62,7 +62,17 @@ type Context struct {
cancelErr error cancelErr error
} }
// NewContext creates a browser context using the parent context. // NewContext creates a chromedp context from the parent context. The parent
// context's Allocator is inherited, defaulting to an ExecAllocator with
// DefaultExecAllocatorOptions.
//
// If the parent context contains an allocated Browser, the child context
// inherits it, and its first Run creates a new tab on that browser. Otherwise,
// its first Run will allocate a new browser.
//
// Cancelling the returned context will close a tab or an entire browser,
// depending on the logic described above. To cancel a context while checking
// for errors, see Cancel.
func NewContext(parent context.Context, opts ...ContextOption) (context.Context, context.CancelFunc) { func NewContext(parent context.Context, opts ...ContextOption) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(parent) ctx, cancel := context.WithCancel(parent)