Skip to content

Commit

Permalink
feat: sendkeys action
Browse files Browse the repository at this point in the history
  • Loading branch information
Davincible committed Jan 6, 2023
1 parent 7e301e5 commit f84b63c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,8 @@ func RunCommandWithRes(method string, params, res any) chromedp.ActionFunc
//
// It's better to use this method than emulation.UserAgentOverride.
func UserAgentOverride(userAgent string) chromedp.ActionFunc

// SendKeys does the same as chromedp.SendKeys excepts it randomly waits 100-500ms
// between sending key presses.
func SendKeys(sel any, v string, opts ...chromedp.QueryOption) chromedp.ActionFunc
```
21 changes: 20 additions & 1 deletion actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"math/rand"
"os"
"time"

Expand Down Expand Up @@ -118,7 +119,7 @@ func SaveCookiesTo(path string) chromedp.ActionFunc {
return err
}

b, err := json.Marshal(c)
b, err := json.MarshalIndent(c, "", " ")
if err != nil {
return err
}
Expand Down Expand Up @@ -161,3 +162,21 @@ func RunCommand(method string, params any) chromedp.ActionFunc {
func BlockURLs(url ...string) chromedp.ActionFunc {
return RunCommand("Network.setBlockedURLs", map[string][]string{"urls": url})
}

// SendKeys does the same as chromedp.SendKeys excepts it randomly waits 100-500ms
// between sending key presses.
func SendKeys(sel any, v string, opts ...chromedp.QueryOption) chromedp.ActionFunc {
return chromedp.ActionFunc(func(ctx context.Context) error {
rand.Seed(time.Now().Unix())

for _, key := range v {
if err := chromedp.SendKeys(sel, string(key), opts...).Do(ctx); err != nil {
return err
}
s := rand.Int63n(100) + 100 //nolint:gosec
time.Sleep(time.Duration(s) * time.Millisecond)
}

return nil
})
}

0 comments on commit f84b63c

Please sign in to comment.