chromedp/actions.go

62 lines
1.6 KiB
Go
Raw Normal View History

2017-01-24 15:09:23 +00:00
package chromedp
import (
"context"
"time"
2017-01-26 07:28:34 +00:00
"github.com/knq/chromedp/cdp"
2017-01-24 15:09:23 +00:00
)
// Action is the common interface for an action that will be executed against a
// context and frame handler.
2017-01-24 15:09:23 +00:00
type Action interface {
// Do executes the action using the provided context and frame handler.
Do(context.Context, cdp.Handler) error
2017-01-24 15:09:23 +00:00
}
// ActionFunc is a adapter to allow the use of ordinary func's as an Action.
type ActionFunc func(context.Context, cdp.Handler) error
2017-01-24 15:09:23 +00:00
// Do executes the func f using the provided context and frame handler.
func (f ActionFunc) Do(ctxt context.Context, h cdp.Handler) error {
2017-01-24 15:09:23 +00:00
return f(ctxt, h)
}
// Tasks is a sequential list of Actions that can be used as a single Action.
2017-01-24 15:09:23 +00:00
type Tasks []Action
// Do executes the list of Actions sequentially, using the provided context and
// frame handler.
func (t Tasks) Do(ctxt context.Context, h cdp.Handler) error {
2017-01-24 15:09:23 +00:00
var err error
// TODO: put individual task timeouts from context here
for _, a := range t {
// ctxt, cancel = context.WithTimeout(ctxt, timeout)
// defer cancel()
err = a.Do(ctxt, h)
if err != nil {
return err
}
}
return nil
}
// Sleep is an empty action that calls time.Sleep with the specified duration.
//
// Note: this is a temporary action definition for convenience, and will likely
// be marked for deprecation in the future, after the remaining Actions have
// been able to be written/tested.
2017-01-24 15:09:23 +00:00
func Sleep(d time.Duration) Action {
return ActionFunc(func(ctxt context.Context, h cdp.Handler) error {
select {
case <-time.After(d):
case <-ctxt.Done():
return ctxt.Err()
}
2017-01-24 15:09:23 +00:00
return nil
})
}