Skip to content

Commit

Permalink
make sure we can close the page while navigating
Browse files Browse the repository at this point in the history
resolve #700
  • Loading branch information
ysmood committed Aug 27, 2022
1 parent 17b8fba commit 635c06d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
6 changes: 6 additions & 0 deletions lib/cdp/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,9 @@ var ErrNodeNotFoundAtPos = &Error{
Code: -32000,
Message: "No node found at given location",
}

// ErrNotAttachedToActivePage type
var ErrNotAttachedToActivePage = &Error{
Code: -32000,
Message: "Not attached to an active page",
}
16 changes: 13 additions & 3 deletions page.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"sync"
"time"

"github.com/go-rod/rod/lib/cdp"
"github.com/go-rod/rod/lib/devices"
"github.com/go-rod/rod/lib/js"
"github.com/go-rod/rod/lib/proto"
Expand Down Expand Up @@ -296,9 +298,17 @@ func (p *Page) Close() error {
defer cancel()
messages := p.browser.Context(ctx).Event()

err := proto.PageClose{}.Call(p)
if err != nil {
return err
for {
err := proto.PageClose{}.Call(p)
if errors.Is(err, cdp.ErrNotAttachedToActivePage) {
// TODO: I don't know why chromium doesn't allow to close a page while it's navigating.
// Looks like a bug in chromium.
utils.Sleep(0.1)
continue
} else if err != nil {
return err
}
break
}

for msg := range messages {
Expand Down
10 changes: 10 additions & 0 deletions page_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,16 @@ func TestPageCloseErr(t *testing.T) {
})
}

func TestPageCloseWhenNotAttached(t *testing.T) {
g := setup(t)

p := g.browser.MustPage(g.blank())

_ = p.Navigate("http://not-exists")

g.E(p.Close())
}

func TestPageAddScriptTag(t *testing.T) {
g := setup(t)

Expand Down

0 comments on commit 635c06d

Please sign in to comment.