How to pause requests in a newly opened tab
saywowowowo opened this issue · comments
saywowowowo commented
What versions are you running?
$ go list -m github.com/chromedp/chromedp
github.com/chromedp/chromedp v0.9.5
$ google-chrome --version
Version 119.0.6045.159 (Official Build) (arm64)
$ go version
go version go1.21.3 darwin/arm64
What did you do? Include clear steps.
I have a page, which contains a tag. When I click on this tag, the browser opens a new tab. At this point, I want to pause requests to demo.com/2.php.
package main
import (
"context"
"fmt"
"github.com/chromedp/cdproto/fetch"
"github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
"goodluck/pkg/logger"
"log"
"net/http"
"net/http/httptest"
"time"
)
func addNewTabListener(ctx context.Context) <-chan target.ID {
mux := http.NewServeMux()
ts := httptest.NewServer(mux)
defer ts.Close()
ch := chromedp.WaitNewTarget(ctx, func(info *target.Info) bool {
if info.URL == "http://a.com/2.php" {
return true
}
return false
})
return ch
}
func main() {
ops := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.NoDefaultBrowserCheck,
chromedp.Flag("headless", false),
chromedp.NoFirstRun,
)
allocCtx, _ := chromedp.NewExecAllocator(context.Background(), ops...)
ctx, cancel := chromedp.NewContext(allocCtx)
defer cancel()
rule := fetch.RequestPattern{
URLPattern: "*2.php*",
RequestStage: "Request",
}
p := make([]*fetch.RequestPattern, 0)
p = append(p, &rule)
if err := chromedp.Run(ctx,
chromedp.Navigate("http://a.com/1.php"),
); err != nil {
logger.GetGoroutineLogger().Warnf("执行任务失败%s", err.Error())
return
}
ch := addNewTabListener(ctx)
dd := <-ch
newCtx, cancel := chromedp.NewContext(ctx, chromedp.WithTargetID(dd))
defer cancel()
// 获取浏览器对象
chromedp.ListenTarget(newCtx, func(ev interface{}) {
switch ev := ev.(type) {
case *fetch.EventRequestPaused:
fmt.Println("pause request:", ev.Request.URL)
}
})
fetchEable := &fetch.EnableParams{
Patterns: p,
HandleAuthRequests: false,
}
// If you use this kind of syntax, it will throw a null pointer error because exec.Target is nil.
//exec := chromedp.FromContext(newCtx)
//if err := fetchEable.Do(cdp.WithExecutor(newCtx, exec.Target)); err != nil {
// fmt.Println(err.Error(), "aaaaaa")
// return
//}
err := chromedp.Run(newCtx,
//fetch.enable.This kind of syntax won't throw an error, but it won't trigger the request pause event either.
fetchEable,
)
if err != nil {
log.Fatal(err)
}
time.Sleep(5000 * time.Second)
}
What did you expect to see?
I would like to pause the request to demo.com/2.php.
What did you see instead?
I observed that the request to demo.com/2.php passed normally without being paused.