Intercept requests
This program loads a page while it blocks the tracker script of the page and answers the API of the page with a greeting of its own. The server of the page sends other answers, which the page never sees.
done

tutorials/intercept/run.go in Chrome/158.0.8127.88. Step through it to see the line of Go, the page and the protocol messages of each step.The steps of the recording
- line 32
if _, err := chromedp.Call(ctx, fetch.Enable, fetch.EnableParams{ - line 46
if err := chromedp.Do(ctx, chromedp.Navigate(url)); err != nil { - line 74
_, err = chromedp.Call(ctx, fetch.FailRequest, fetch.FailRequestParams{ - line 79
_, err = chromedp.Call(ctx, fetch.FulfillRequest, fetch.FulfillRequestParams{ - line 51
if _, err := chromedp.Run(ctx, chromedp.Poll[bool](`document.title === "done"`)); err != nil { - line 54
text, err := chromedp.Run(ctx, chromedp.Text(chromedp.CSS("#out")))
The program
Section titled “The program”package main
import (
"context"
"fmt"
"io"
"iter"
"strings"
"github.com/chromedp/cdproto/fetch"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
)
// run loads the page at url while it blocks the tracker of the page and
// answers its API with a greeting of its own, and prints what the page shows.
func run(ctx context.Context, w io.Writer, url string) error {
// An empty Do starts the browser on ctx. The handler below uses a
// context that ends before ctx, and the browser must not end with it.
if err := chromedp.Do(ctx); err != nil {
return fmt.Errorf("starting the browser: %w", err)
}
// Subscribe to the paused requests before Fetch.enable, so that no
// request is lost.
handlerCtx, stop := context.WithCancel(ctx)
defer stop()
paused := chromedp.Events(handlerCtx, fetch.RequestPaused)
// The browser pauses each request that matches a pattern, until the
// program answers it. The page itself matches no pattern.
if _, err := chromedp.Call(ctx, fetch.Enable, fetch.EnableParams{
Patterns: []*fetch.RequestPattern{
{URLPattern: "*/api/*"},
{URLPattern: "*/tracker.js"},
},
}); err != nil {
return fmt.Errorf("enabling the Fetch domain: %w", err)
}
// The handler runs in its own goroutine, because the page waits for its
// answers while the navigation below waits for the page.
done := make(chan error, 1)
go func() { done <- handle(ctx, paused) }()
if err := chromedp.Do(ctx, chromedp.Navigate(url)); err != nil {
return fmt.Errorf("loading the page: %w", err)
}
// The script of the page sets the title when it has the greeting.
if _, err := chromedp.Run(ctx, chromedp.Poll[bool](`document.title === "done"`)); err != nil {
return fmt.Errorf("waiting for the page: %w", err)
}
text, err := chromedp.Run(ctx, chromedp.Text(chromedp.CSS("#out")))
if err != nil {
return fmt.Errorf("reading the page: %w", err)
}
fmt.Fprintf(w, "the page shows:\n%s\n", text)
stop()
return <-done
}
// handle answers each paused request: it blocks the tracker, answers the API
// with a greeting, and lets any other request go on.
func handle(ctx context.Context, paused iter.Seq2[fetch.EventRequestPaused, error]) error {
for ev, err := range paused {
if err != nil {
// The subscription ends when run calls stop.
return nil
}
switch {
case strings.HasSuffix(ev.Request.URL, "/tracker.js"):
_, err = chromedp.Call(ctx, fetch.FailRequest, fetch.FailRequestParams{
RequestID: ev.RequestID,
ErrorReason: network.ErrorReasonBlockedByClient,
})
case strings.Contains(ev.Request.URL, "/api/"):
_, err = chromedp.Call(ctx, fetch.FulfillRequest, fetch.FulfillRequestParams{
RequestID: ev.RequestID,
ResponseCode: 200,
ResponseHeaders: []*fetch.HeaderEntry{{Name: "Content-Type", Value: "application/json"}},
Body: []byte(`{"text":"Hello from chromedp"}`),
})
default:
_, err = chromedp.Call(ctx, fetch.ContinueRequest, fetch.ContinueRequestParams{RequestID: ev.RequestID})
}
if err != nil {
return fmt.Errorf("answering %s: %w", ev.Request.URL, err)
}
}
return nil
}// Command intercept is the program of the tutorial "Intercept requests" on
// https://chromedp.dev. It blocks one request of a page and answers another one with data of its own.
//
// go run .
package main
import (
"context"
"log"
"net/http/httptest"
"os"
"time"
"github.com/chromedp/chromedp"
)
func main() {
// Serve the page of the tutorial on this computer, so that the program
// needs no internet.
srv := httptest.NewServer(handler())
defer srv.Close()
// The context holds the browser. The first call on it starts Chrome, and
// cancel stops Chrome.
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// A timeout keeps the program from waiting for ever.
ctx, cancel = context.WithTimeout(ctx, 30*time.Second)
defer cancel()
if err := run(ctx, os.Stdout, srv.URL); err != nil {
log.Fatal(err)
}
}package main
import (
_ "embed"
"net/http"
)
//go:embed page.html
var page []byte
// handler serves the page of the tutorial, its API and its tracker. The
// program answers the API and blocks the tracker, so the page shows none of
// what the server sends for them.
func handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(page)
})
mux.HandleFunc("/api/greeting", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"text":"Hello from the server"}`))
})
mux.HandleFunc("/tracker.js", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/javascript")
w.Write([]byte(`document.getElementById("tracker").textContent = "The tracker ran.";`))
})
return mux
}The page of the program is page.html. In a folder with the four files, go run . prints:
the page shows:The API says: Hello from chromedp
The tracker did not run.How it works
Section titled “How it works”The Fetch domain of the protocol pauses each request that matches a
pattern, until the program answers it. The program:
- Subscribes to the event
fetch.RequestPausedwithchromedp.Events, before it turns the domain on, so that no paused request is lost. - Turns the domain on with
fetch.Enable, with a pattern for the API and one for the tracker. The page itself matches no pattern, so it loads as usual. - Answers each paused request in a goroutine of its own. The page waits for these answers while the navigation waits for the page, so the answers cannot come from the goroutine that navigates.
The handler answers in one of three ways:
| Command | What the page gets |
|---|---|
fetch.FailRequest |
an error, as if the network blocked the request |
fetch.FulfillRequest |
the status, the headers and the body that the program gives |
fetch.ContinueRequest |
the answer of the server, as if nothing paused the request |
chromedp.Poll waits until the script of the page sets the title to done.
Then the program stops the handler and prints the page.