playwright-community / playwright-go

Playwright for Go a browser automation library to control Chromium, Firefox and WebKit with a single API.
https://playwright-community.github.io/playwright-go/
MIT License
2.11k stars 156 forks source link

Nil browser context options when using Chromium.ConnectOverCDP with an existing browser context #360

Closed Sacrond closed 1 year ago

Sacrond commented 1 year ago
// Start playwright
pw, err := playwright.Run()
if err != nil {
    fmt.Printf("Error detected: %v", err)
}

// Attach playwright to browser
browser, err := pw.Chromium.ConnectOverCDP(fmt.Sprintf("ws://127.0.0.1:%v%v", browserInfo.Port, browserInfo.WsEndPoint))
if err != nil {
    fmt.Printf("Error detected: %v", err)
}

// Initialize page
var page playwright.Page

// Get first page of browser if opened
if c := browser.Contexts(); len(c) > 0 {
    if p := c[0].Pages(); len(p) > 0 {
        page = p[0]
    }
}

// Get routes
page.Route("*/**", func(r playwright.Route) {
    fmt.Println(r.Request().ResourceType())
    r.Continue()
})

Will get the following panic:

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x8 pc=0x9cacb6]

goroutine 1 [running]:
github.com/playwright-community/playwright-go.(*pageImpl).Route(0xc0000d8500, {0xa11bc0, 0xb43840}, 0xadf5a8, {0x0, 0x0, 0xc000016dc0?})
C:/Users/Compy/go/pkg/mod/github.com/playwright-community/playwright-go@v0.3500.0/page.go:601 +0xb6

Triggered from the following Route function inside page.go:

func (p *pageImpl) Route(url interface{}, handler routeHandler, times ...int) error {
    p.Lock()
    defer p.Unlock()
    p.routes = append(p.routes, newRouteHandlerEntry(newURLMatcher(url, p.browserContext.options.BaseURL), handler, times...))
    return p.updateInterceptionPatterns()
}

Upon checking, it seems like p.browserContext.options is nil.

Suggestion:

func (p *pageImpl) Route(url interface{}, handler routeHandler, times ...int) error {
    p.Lock()
    defer p.Unlock()
    var baseURL *string
    if p.browserContext.options != nil {
        baseURL = p.browserContext.options.BaseURL
    }
    p.routes = append(p.routes, newRouteHandlerEntry(newURLMatcher(url, baseURL), handler, times...))
    return p.updateInterceptionPatterns()
}