chromedp / chromedp

A faster, simpler way to drive browsers supporting the Chrome DevTools Protocol.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why the ctx cancel, and its parent ctx cancel too.

CoronaAustralis opened this issue · comments

What versions are you running?

$ go list -m github.com/chromedp/chromedp
github.com/chromedp/chromedp v0.9.5
$ google-chrome --version
122.0.6261.111
$ go version
go version go1.21.0 windows/amd64

What did you do? Include clear steps.

taskCtx, cancel := chromedp.NewContext(allocCtx)
chromedp.Run(taskCtx)
defer cancel()	

ch := make(chan bool)
openAndLogin(taskCtx,ch)
<- ch
time.Sleep(time.Second * 10000)


func openAndLogin(ctx context.Context, ch chan bool){
	loginCtx, cancel := chromedp.NewContext(ctx)
	chromedp.ListenTarget(loginCtx, func(ev interface{}) {
		switch ev := ev.(type) {
		case *network.EventResponseReceived:
			resp := ev.Response
			if resp.URL == "http://192.168.1.1/test/" {
				go func() {
					c := chromedp.FromContext(loginCtx)
					rbp := network.GetResponseBody(ev.RequestID)
					body, err := rbp.Do(cdp.WithExecutor(loginCtx, c.Target))
					if err != nil {
						log.Panicln(err)
					}

					var json_resp LoginGet
					json.Unmarshal(body, &json_resp)
					if json_resp.Error == 0 {
						ch <- true
						cancel()
					}
				}()
			}
		}
	})

	err := chromedp.Run(loginCtx, chromedp.Navigate("http://192.168.1.1"))
	if err != nil {
		log.Fatal(err)
	}
}

This code runs normally, but I changed openAndLogin(taskCtx,ch) to go openAndLogin(taskCtx,ch), and the code ended directly, prompting context canceled, and the time.sleep did not run. I want to know why.

What did you expect to see?

Code runs normally

What did you see instead?

Code ended directly