chromedp / chromedp

A faster, simpler way to drive browsers supporting the Chrome DevTools Protocol.
MIT License
11.13k stars 792 forks source link

(Mac OS) When I click X to close the browser,the program cannot trigger context canceled. #800

Closed mrlayki closed 3 years ago

mrlayki commented 3 years ago

What versions are you running?

$ go list -m github.com/chromedp/chromedp
github.com/chromedp/chromedp v0.6.10
$ google-chrome --version
89.0.4389.114(x86_64)
$ go version
go version go1.16.3 darwin/amd64

What did you do? Include clear steps.

(Mac OS) When I click X to close the browser, the browser does not exit completely. At this time, the program cannot trigger context canceled.

What did you expect to see?

How should I code to trigger context canceled to end the task when I click X to close the browser? In other words, how should I code to make it completely close when I click X to close the browser?

My code:

       tik.ctx, tik.cancel = chromedpEngine.NewExecCtx(
        chromedp.ExecPath(execPath),
        chromedp.UserAgent(tik.userAgent),
        chromedp.UserDataDir(tik.userDataDir+tik.port),
    )

    defer tik.cancel()
    if err := chromedp.Run(tik.ctx, tik.uploadTasks()); err != nil {
        logs.Println("fail")
        return "fail"
    }
    if tik.isUpload == true {
        logs.Println("success")
        return "success"
    } else {
        logs.Println("fail")
        return "fail"
    }

func NewExecCtx(opts ...chromedp.ExecAllocatorOption) (context.Context, context.CancelFunc) {
    topC, _ := context.WithCancel(GetGlobalCtx())
    c, _ := chromedp.NewExecAllocator(topC, CreateOptions(opts...)...)
    ctx, cancel := chromedp.NewContext(c)
    return ctx, cancel
}
mrlayki commented 3 years ago

@ZekeLu help......

ZekeLu commented 3 years ago

Please read this thread first: https://stackoverflow.com/questions/5480114/os-x-design-decisions-terminate-the-app-on-last-window-close. On MacOS, the Chrome process won't terminate when all its window are closed. You can use +Q to terminate the Chrome process.

And I guess you want to do something in your code when the Chrome process is terminated. This is what you need:

<-chromedp.FromContext(ctx).Browser.LostConnection

https://github.com/chromedp/chromedp/blob/5b511f121cb2fc1e868b8667049d3cff32a6e0b1/browser.go#L31-L34

mrlayki commented 3 years ago

Thanks