vendor/github.com/go-rod/rod/page.go

1061 lines · 28312 bytes

   1package rod
   2
   3import (
   4	"context"
   5	"crypto/md5"
   6	"encoding/base64"
   7	"encoding/hex"
   8	"errors"
   9	"fmt"
  10	"sync"
  11	"time"
  12
  13	"github.com/go-rod/rod/lib/cdp"
  14	"github.com/go-rod/rod/lib/devices"
  15	"github.com/go-rod/rod/lib/js"
  16	"github.com/go-rod/rod/lib/proto"
  17	"github.com/go-rod/rod/lib/utils"
  18	"github.com/ysmood/goob"
  19	"github.com/ysmood/got/lib/lcs"
  20	"github.com/ysmood/gson"
  21)
  22
  23// Page implements these interfaces.
  24var (
  25	_ proto.Client      = &Page{}
  26	_ proto.Contextable = &Page{}
  27	_ proto.Sessionable = &Page{}
  28)
  29
  30// Page represents the webpage.
  31// We try to hold as less states as possible.
  32// When a page is closed by Rod or not all the ongoing operations an events on it will abort.
  33type Page struct {
  34	// TargetID is a unique ID for a remote page.
  35	// It's usually used in events sent from the browser to tell which page an event belongs to.
  36	TargetID proto.TargetTargetID
  37
  38	// FrameID is a unique ID for a browsing context.
  39	// Usually, different FrameID means different javascript execution context.
  40	// Such as an iframe and the page it belongs to will have the same TargetID but different FrameIDs.
  41	FrameID proto.PageFrameID
  42
  43	// SessionID is a unique ID for a page attachment to a controller.
  44	// It's usually used in transport layer to tell which page to send the control signal.
  45	// A page can attached to multiple controllers, the browser uses it distinguish controllers.
  46	SessionID proto.TargetSessionID
  47
  48	e eFunc
  49
  50	ctx context.Context
  51
  52	// Used to abort all ongoing actions when a page closes.
  53	sessionCancel func()
  54
  55	root *Page
  56
  57	sleeper func() utils.Sleeper
  58
  59	browser *Browser
  60	event   *goob.Observable
  61
  62	// devices
  63	Mouse    *Mouse
  64	Keyboard *Keyboard
  65	Touch    *Touch
  66
  67	element *Element // iframe only
  68
  69	jsCtxLock   *sync.Mutex
  70	jsCtxID     *proto.RuntimeRemoteObjectID // use pointer so that page clones can share the change
  71	helpersLock *sync.Mutex
  72	helpers     map[proto.RuntimeRemoteObjectID]map[string]proto.RuntimeRemoteObjectID
  73}
  74
  75// String interface.
  76func (p *Page) String() string {
  77	id := p.TargetID
  78	if len(id) > 8 {
  79		id = id[:8]
  80	}
  81	return fmt.Sprintf("<page:%s>", id)
  82}
  83
  84// IsIframe tells if it's iframe.
  85func (p *Page) IsIframe() bool {
  86	return p.element != nil
  87}
  88
  89// GetSessionID interface.
  90func (p *Page) GetSessionID() proto.TargetSessionID {
  91	return p.SessionID
  92}
  93
  94// Browser of the page.
  95func (p *Page) Browser() *Browser {
  96	return p.browser
  97}
  98
  99// Info of the page, such as the URL or title of the page.
 100func (p *Page) Info() (*proto.TargetTargetInfo, error) {
 101	return p.browser.pageInfo(p.TargetID)
 102}
 103
 104// HTML of the page.
 105func (p *Page) HTML() (string, error) {
 106	el, err := p.Element("html")
 107	if err != nil {
 108		return "", err
 109	}
 110	return el.HTML()
 111}
 112
 113// Cookies returns the page cookies. By default it will return the cookies for current page.
 114// The urls is the list of URLs for which applicable cookies will be fetched.
 115func (p *Page) Cookies(urls []string) ([]*proto.NetworkCookie, error) {
 116	if len(urls) == 0 {
 117		info, err := p.Info()
 118		if err != nil {
 119			return nil, err
 120		}
 121		urls = []string{info.URL}
 122	}
 123
 124	res, err := proto.NetworkGetCookies{Urls: urls}.Call(p)
 125	if err != nil {
 126		return nil, err
 127	}
 128	return res.Cookies, nil
 129}
 130
 131// SetCookies is similar to Browser.SetCookies .
 132func (p *Page) SetCookies(cookies []*proto.NetworkCookieParam) error {
 133	if cookies == nil {
 134		return proto.NetworkClearBrowserCookies{}.Call(p)
 135	}
 136	return proto.NetworkSetCookies{Cookies: cookies}.Call(p)
 137}
 138
 139// SetExtraHeaders whether to always send extra HTTP headers with the requests from this page.
 140func (p *Page) SetExtraHeaders(dict []string) (func(), error) {
 141	headers := proto.NetworkHeaders{}
 142
 143	for i := 0; i < len(dict); i += 2 {
 144		headers[dict[i]] = gson.New(dict[i+1])
 145	}
 146
 147	return p.EnableDomain(&proto.NetworkEnable{}), proto.NetworkSetExtraHTTPHeaders{Headers: headers}.Call(p)
 148}
 149
 150// SetUserAgent (browser brand, accept-language, etc) of the page.
 151// If req is nil, a default user agent will be used, a typical mac chrome.
 152func (p *Page) SetUserAgent(req *proto.NetworkSetUserAgentOverride) error {
 153	if req == nil {
 154		req = devices.LaptopWithMDPIScreen.UserAgentEmulation()
 155	}
 156	return req.Call(p)
 157}
 158
 159// SetBlockedURLs For some requests that do not want to be triggered,
 160// such as some dangerous operations, delete, quit logout, etc.
 161// Wildcards ('*') are allowed, such as ["*/api/logout/*","delete"].
 162// NOTE: if you set empty pattern "", it will block all requests.
 163func (p *Page) SetBlockedURLs(urls []string) error {
 164	if len(urls) == 0 {
 165		return nil
 166	}
 167	return proto.NetworkSetBlockedURLs{Urls: urls}.Call(p)
 168}
 169
 170// Navigate to the url. If the url is empty, "about:blank" will be used.
 171// It will return immediately after the server responds the http header.
 172func (p *Page) Navigate(url string) error {
 173	if url == "" {
 174		url = "about:blank"
 175	}
 176
 177	// try to stop loading
 178	_ = p.StopLoading()
 179
 180	res, err := proto.PageNavigate{URL: url}.Call(p)
 181	if err != nil {
 182		return err
 183	}
 184	if res.ErrorText != "" {
 185		return &NavigationError{res.ErrorText}
 186	}
 187
 188	p.root.unsetJSCtxID()
 189
 190	return nil
 191}
 192
 193// NavigateBack history.
 194func (p *Page) NavigateBack() error {
 195	// Not using cdp API because it doesn't work for iframe
 196	_, err := p.Evaluate(Eval(`() => history.back()`).ByUser())
 197	return err
 198}
 199
 200// ResetNavigationHistory reset history.
 201func (p *Page) ResetNavigationHistory() error {
 202	err := proto.PageResetNavigationHistory{}.Call(p)
 203	return err
 204}
 205
 206// GetNavigationHistory get navigation history.
 207func (p *Page) GetNavigationHistory() (*proto.PageGetNavigationHistoryResult, error) {
 208	return proto.PageGetNavigationHistory{}.Call(p)
 209}
 210
 211// NavigateForward history.
 212func (p *Page) NavigateForward() error {
 213	// Not using cdp API because it doesn't work for iframe
 214	_, err := p.Evaluate(Eval(`() => history.forward()`).ByUser())
 215	return err
 216}
 217
 218// Reload page.
 219func (p *Page) Reload() error {
 220	p, cancel := p.WithCancel()
 221	defer cancel()
 222
 223	wait := p.EachEvent(func(e *proto.PageFrameNavigated) bool {
 224		return e.Frame.ID == p.FrameID
 225	})
 226
 227	// Not using cdp API because it doesn't work for iframe
 228	_, err := p.Evaluate(Eval(`() => location.reload()`).ByUser())
 229	if err != nil {
 230		return err
 231	}
 232
 233	wait()
 234
 235	p.unsetJSCtxID()
 236
 237	return nil
 238}
 239
 240// Activate (focuses) the page.
 241func (p *Page) Activate() (*Page, error) {
 242	err := proto.TargetActivateTarget{TargetID: p.TargetID}.Call(p.browser)
 243	return p, err
 244}
 245
 246func (p *Page) getWindowID() (proto.BrowserWindowID, error) {
 247	res, err := proto.BrowserGetWindowForTarget{TargetID: p.TargetID}.Call(p)
 248	if err != nil {
 249		return 0, err
 250	}
 251	return res.WindowID, err
 252}
 253
 254// GetWindow position and size info.
 255func (p *Page) GetWindow() (*proto.BrowserBounds, error) {
 256	id, err := p.getWindowID()
 257	if err != nil {
 258		return nil, err
 259	}
 260
 261	res, err := proto.BrowserGetWindowBounds{WindowID: id}.Call(p)
 262	if err != nil {
 263		return nil, err
 264	}
 265
 266	return res.Bounds, nil
 267}
 268
 269// SetWindow location and size.
 270func (p *Page) SetWindow(bounds *proto.BrowserBounds) error {
 271	id, err := p.getWindowID()
 272	if err != nil {
 273		return err
 274	}
 275
 276	err = proto.BrowserSetWindowBounds{WindowID: id, Bounds: bounds}.Call(p)
 277	return err
 278}
 279
 280// SetViewport overrides the values of device screen dimensions.
 281func (p *Page) SetViewport(params *proto.EmulationSetDeviceMetricsOverride) error {
 282	if params == nil {
 283		return proto.EmulationClearDeviceMetricsOverride{}.Call(p)
 284	}
 285	return params.Call(p)
 286}
 287
 288// SetDocumentContent sets the page document html content.
 289func (p *Page) SetDocumentContent(html string) error {
 290	return proto.PageSetDocumentContent{
 291		FrameID: p.FrameID,
 292		HTML:    html,
 293	}.Call(p)
 294}
 295
 296// Emulate the device, such as iPhone9. If device is devices.Clear, it will clear the override.
 297func (p *Page) Emulate(device devices.Device) error {
 298	err := p.SetViewport(device.MetricsEmulation())
 299	if err != nil {
 300		return err
 301	}
 302
 303	err = device.TouchEmulation().Call(p)
 304	if err != nil {
 305		return err
 306	}
 307
 308	return p.SetUserAgent(device.UserAgentEmulation())
 309}
 310
 311// StopLoading forces the page stop navigation and pending resource fetches.
 312func (p *Page) StopLoading() error {
 313	return proto.PageStopLoading{}.Call(p)
 314}
 315
 316// Close tries to close page, running its beforeunload hooks, if has any.
 317func (p *Page) Close() error {
 318	p.browser.targetsLock.Lock()
 319	defer p.browser.targetsLock.Unlock()
 320
 321	success := true
 322	ctx, cancel := context.WithCancel(p.ctx)
 323	defer cancel()
 324	messages := p.browser.Context(ctx).Event()
 325
 326	for {
 327		err := proto.PageClose{}.Call(p)
 328		if errors.Is(err, cdp.ErrNotAttachedToActivePage) {
 329			// TODO: I don't know why chromium doesn't allow us to close a page while it's navigating.
 330			// Looks like a bug in chromium.
 331			utils.Sleep(0.1)
 332			continue
 333		} else if err != nil {
 334			return err
 335		}
 336		break
 337	}
 338
 339	for msg := range messages {
 340		stop := false
 341
 342		destroyed := proto.TargetTargetDestroyed{}
 343		closed := proto.PageJavascriptDialogClosed{}
 344		if msg.Load(&destroyed) {
 345			stop = destroyed.TargetID == p.TargetID
 346		} else if msg.SessionID == p.SessionID && msg.Load(&closed) {
 347			success = closed.Result
 348			stop = !success
 349		}
 350
 351		if stop {
 352			break
 353		}
 354	}
 355
 356	if success {
 357		p.cleanupStates()
 358	} else {
 359		return &PageCloseCanceledError{}
 360	}
 361
 362	return nil
 363}
 364
 365// TriggerFavicon supports when browser in headless mode
 366// to trigger favicon's request. Pay attention to this
 367// function only supported when browser in headless mode,
 368// if you call it in no-headless mode, it will raise an error
 369// with the message "browser is no-headless".
 370func (p *Page) TriggerFavicon() error {
 371	// check if browser whether in headless mode
 372	// if not in headless mode then raise error
 373	if !p.browser.isHeadless() {
 374		return errors.New("browser is no-headless")
 375	}
 376
 377	_, err := p.Evaluate(evalHelper(js.TriggerFavicon).ByPromise())
 378	if err != nil {
 379		return err
 380	}
 381	return nil
 382}
 383
 384// HandleDialog accepts or dismisses next JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload).
 385// Because modal dialog will block js, usually you have to trigger the dialog in another goroutine.
 386// For example:
 387//
 388//	wait, handle := page.MustHandleDialog()
 389//	go page.MustElement("button").MustClick()
 390//	wait()
 391//	handle(true, "")
 392func (p *Page) HandleDialog() (
 393	wait func() *proto.PageJavascriptDialogOpening,
 394	handle func(*proto.PageHandleJavaScriptDialog) error,
 395) {
 396	restore := p.EnableDomain(&proto.PageEnable{})
 397
 398	var e proto.PageJavascriptDialogOpening
 399	w := p.WaitEvent(&e)
 400
 401	return func() *proto.PageJavascriptDialogOpening {
 402			w()
 403			return &e
 404		}, func(h *proto.PageHandleJavaScriptDialog) error {
 405			defer restore()
 406			return h.Call(p)
 407		}
 408}
 409
 410// HandleFileDialog return a functions that waits for the next file chooser dialog pops up and returns the element
 411// for the event.
 412func (p *Page) HandleFileDialog() (func([]string) error, error) {
 413	err := proto.PageSetInterceptFileChooserDialog{Enabled: true}.Call(p)
 414	if err != nil {
 415		return nil, err
 416	}
 417
 418	var e proto.PageFileChooserOpened
 419	w := p.WaitEvent(&e)
 420
 421	return func(paths []string) error {
 422		w()
 423
 424		err := proto.PageSetInterceptFileChooserDialog{Enabled: false}.Call(p)
 425		if err != nil {
 426			return err
 427		}
 428
 429		return proto.DOMSetFileInputFiles{
 430			Files:         utils.AbsolutePaths(paths),
 431			BackendNodeID: e.BackendNodeID,
 432		}.Call(p)
 433	}, nil
 434}
 435
 436// Screenshot captures the screenshot of current page.
 437func (p *Page) Screenshot(fullPage bool, req *proto.PageCaptureScreenshot) ([]byte, error) {
 438	if req == nil {
 439		req = &proto.PageCaptureScreenshot{}
 440	}
 441	if fullPage {
 442		metrics, err := proto.PageGetLayoutMetrics{}.Call(p)
 443		if err != nil {
 444			return nil, err
 445		}
 446
 447		if metrics.CSSContentSize == nil {
 448			return nil, errors.New("failed to get css content size")
 449		}
 450
 451		oldView := proto.EmulationSetDeviceMetricsOverride{}
 452		set := p.LoadState(&oldView)
 453		view := oldView
 454		view.Width = int(metrics.CSSContentSize.Width)
 455		view.Height = int(metrics.CSSContentSize.Height)
 456
 457		err = p.SetViewport(&view)
 458		if err != nil {
 459			return nil, err
 460		}
 461
 462		defer func() { // try to recover the viewport
 463			if !set {
 464				_ = proto.EmulationClearDeviceMetricsOverride{}.Call(p)
 465				return
 466			}
 467
 468			_ = p.SetViewport(&oldView)
 469		}()
 470	}
 471
 472	shot, err := req.Call(p)
 473	if err != nil {
 474		return nil, err
 475	}
 476	return shot.Data, nil
 477}
 478
 479// ScrollScreenshotOptions is the options for the ScrollScreenshot.
 480type ScrollScreenshotOptions struct {
 481	// Format (optional) Image compression format (defaults to png).
 482	Format proto.PageCaptureScreenshotFormat `json:"format,omitempty"`
 483
 484	// Quality (optional) Compression quality from range [0..100] (jpeg only).
 485	Quality *int `json:"quality,omitempty"`
 486
 487	// FixedTop (optional) The number of pixels to skip from the top.
 488	// It is suitable for optimizing the screenshot effect when there is a fixed
 489	// positioning element at the top of the page.
 490	FixedTop float64
 491
 492	// FixedBottom (optional) The number of pixels to skip from the bottom.
 493	FixedBottom float64
 494
 495	// WaitPerScroll until no animation (default is 300ms)
 496	WaitPerScroll time.Duration
 497}
 498
 499// ScrollScreenshot Scroll screenshot does not adjust the size of the viewport,
 500// but achieves it by scrolling and capturing screenshots in a loop, and then stitching them together.
 501// Note that this method also has a flaw: when there are elements with fixed
 502// positioning on the page (usually header navigation components),
 503// these elements will appear repeatedly, you can set the FixedTop parameter to optimize it.
 504//
 505// Only support png and jpeg format yet, webP is not supported because no suitable processing
 506// library was found in golang.
 507func (p *Page) ScrollScreenshot(opt *ScrollScreenshotOptions) ([]byte, error) {
 508	if opt == nil {
 509		opt = &ScrollScreenshotOptions{}
 510	}
 511	if opt.WaitPerScroll == 0 {
 512		opt.WaitPerScroll = time.Millisecond * 300
 513	}
 514
 515	metrics, err := proto.PageGetLayoutMetrics{}.Call(p)
 516	if err != nil {
 517		return nil, err
 518	}
 519
 520	if metrics.CSSContentSize == nil || metrics.CSSVisualViewport == nil {
 521		return nil, errors.New("failed to get css content size")
 522	}
 523
 524	viewpointHeight := metrics.CSSVisualViewport.ClientHeight
 525	contentHeight := metrics.CSSContentSize.Height
 526
 527	var scrollTop float64
 528	var images []utils.ImgWithBox
 529
 530	for {
 531		clip := &proto.PageViewport{
 532			X:     0,
 533			Y:     scrollTop,
 534			Width: metrics.CSSVisualViewport.ClientWidth,
 535			Scale: 1,
 536		}
 537
 538		scrollY := viewpointHeight - (opt.FixedTop + opt.FixedBottom)
 539		if scrollTop+viewpointHeight > contentHeight {
 540			clip.Height = contentHeight - scrollTop
 541		} else {
 542			clip.Height = scrollY
 543			if scrollTop != 0 {
 544				clip.Y += opt.FixedTop
 545			}
 546		}
 547
 548		req := &proto.PageCaptureScreenshot{
 549			Format:                opt.Format,
 550			Quality:               opt.Quality,
 551			Clip:                  clip,
 552			FromSurface:           false,
 553			CaptureBeyondViewport: false,
 554			OptimizeForSpeed:      false,
 555		}
 556		shot, err := req.Call(p)
 557		if err != nil {
 558			return nil, err
 559		}
 560
 561		images = append(images, utils.ImgWithBox{Img: shot.Data})
 562
 563		scrollTop += scrollY
 564		if scrollTop >= contentHeight {
 565			break
 566		}
 567
 568		err = p.Mouse.Scroll(0, scrollY, 1)
 569		if err != nil {
 570			return nil, fmt.Errorf("scroll error: %w", err)
 571		}
 572
 573		err = p.WaitDOMStable(opt.WaitPerScroll, 0)
 574		if err != nil {
 575			return nil, fmt.Errorf("WaitDOMStable error: %w", err)
 576		}
 577	}
 578
 579	var imgOption *utils.ImgOption
 580	if opt.Quality != nil {
 581		imgOption = &utils.ImgOption{
 582			Quality: *opt.Quality,
 583		}
 584	}
 585	bs, err := utils.SplicePngVertical(images, opt.Format, imgOption)
 586	if err != nil {
 587		return nil, err
 588	}
 589
 590	return bs, nil
 591}
 592
 593// CaptureDOMSnapshot Returns a document snapshot, including the full DOM tree of the root node
 594// (including iframes, template contents, and imported documents) in a flattened array,
 595// as well as layout and white-listed computed style information for the nodes.
 596// Shadow DOM in the returned DOM tree is flattened.
 597// `Documents` The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document.
 598// `Strings` Shared string table that all string properties refer to with indexes.
 599// Normally use `Strings` is enough.
 600func (p *Page) CaptureDOMSnapshot() (domSnapshot *proto.DOMSnapshotCaptureSnapshotResult, err error) {
 601	_ = proto.DOMSnapshotEnable{}.Call(p)
 602
 603	snapshot, err := proto.DOMSnapshotCaptureSnapshot{
 604		ComputedStyles:                 []string{},
 605		IncludePaintOrder:              true,
 606		IncludeDOMRects:                true,
 607		IncludeBlendedBackgroundColors: true,
 608		IncludeTextColorOpacities:      true,
 609	}.Call(p)
 610	if err != nil {
 611		return nil, err
 612	}
 613	return snapshot, nil
 614}
 615
 616// PDF prints page as PDF.
 617func (p *Page) PDF(req *proto.PagePrintToPDF) (*StreamReader, error) {
 618	req.TransferMode = proto.PagePrintToPDFTransferModeReturnAsStream
 619	res, err := req.Call(p)
 620	if err != nil {
 621		return nil, err
 622	}
 623
 624	return NewStreamReader(p, res.Stream), nil
 625}
 626
 627// GetResource content by the url. Such as image, css, html, etc.
 628// Use the [proto.PageGetResourceTree] to list all the resources.
 629func (p *Page) GetResource(url string) ([]byte, error) {
 630	res, err := proto.PageGetResourceContent{
 631		FrameID: p.FrameID,
 632		URL:     url,
 633	}.Call(p)
 634	if err != nil {
 635		return nil, err
 636	}
 637
 638	data := res.Content
 639
 640	var bin []byte
 641	if res.Base64Encoded {
 642		bin, err = base64.StdEncoding.DecodeString(data)
 643		utils.E(err)
 644	} else {
 645		bin = []byte(data)
 646	}
 647
 648	return bin, nil
 649}
 650
 651// WaitOpen waits for the next new page opened by the current one.
 652func (p *Page) WaitOpen() func() (*Page, error) {
 653	var targetID proto.TargetTargetID
 654
 655	b := p.browser.Context(p.ctx)
 656	wait := b.EachEvent(func(e *proto.TargetTargetCreated) bool {
 657		targetID = e.TargetInfo.TargetID
 658		return e.TargetInfo.OpenerID == p.TargetID
 659	})
 660
 661	return func() (*Page, error) {
 662		defer p.tryTrace(TraceTypeWait, "wait open")()
 663		wait()
 664		return b.PageFromTarget(targetID)
 665	}
 666}
 667
 668// EachEvent of the specified event types, if any callback returns true the wait function will resolve,
 669// The type of each callback is (? means optional):
 670//
 671//	func(proto.Event, proto.TargetSessionID?) bool?
 672//
 673// You can listen to multiple event types at the same time like:
 674//
 675//	browser.EachEvent(func(a *proto.A) {}, func(b *proto.B) {})
 676//
 677// Such as subscribe the events to know when the navigation is complete or when the page is rendered.
 678// Here's an example to dismiss all dialogs/alerts on the page:
 679//
 680//	go page.EachEvent(func(e *proto.PageJavascriptDialogOpening) {
 681//	    _ = proto.PageHandleJavaScriptDialog{ Accept: false, PromptText: ""}.Call(page)
 682//	})()
 683func (p *Page) EachEvent(callbacks ...interface{}) (wait func()) {
 684	return p.browser.Context(p.ctx).eachEvent(p.SessionID, callbacks...)
 685}
 686
 687// WaitEvent waits for the next event for one time. It will also load the data into the event object.
 688func (p *Page) WaitEvent(e proto.Event) (wait func()) {
 689	defer p.tryTrace(TraceTypeWait, "event", e.ProtoEvent())()
 690	return p.browser.Context(p.ctx).waitEvent(p.SessionID, e)
 691}
 692
 693// WaitNavigation wait for a page lifecycle event when navigating.
 694// Usually you will wait for [proto.PageLifecycleEventNameNetworkAlmostIdle].
 695func (p *Page) WaitNavigation(name proto.PageLifecycleEventName) func() {
 696	_ = proto.PageSetLifecycleEventsEnabled{Enabled: true}.Call(p)
 697
 698	wait := p.EachEvent(func(e *proto.PageLifecycleEvent) bool {
 699		return e.Name == name
 700	})
 701
 702	return func() {
 703		defer p.tryTrace(TraceTypeWait, "navigation", name)()
 704		wait()
 705		_ = proto.PageSetLifecycleEventsEnabled{Enabled: false}.Call(p)
 706	}
 707}
 708
 709// WaitRequestIdle returns a wait function that waits until no request for d duration.
 710// Be careful, d is not the max wait timeout, it's the least idle time.
 711// If you want to set a timeout you can use the [Page.Timeout] function.
 712// Use the includes and excludes regexp list to filter the requests by their url.
 713func (p *Page) WaitRequestIdle(
 714	d time.Duration,
 715	includes, excludes []string,
 716	excludeTypes []proto.NetworkResourceType,
 717) func() {
 718	defer p.tryTrace(TraceTypeWait, "request-idle")()
 719
 720	if excludeTypes == nil {
 721		excludeTypes = []proto.NetworkResourceType{
 722			proto.NetworkResourceTypeWebSocket,
 723			proto.NetworkResourceTypeEventSource,
 724			proto.NetworkResourceTypeMedia,
 725			proto.NetworkResourceTypeImage,
 726			proto.NetworkResourceTypeFont,
 727		}
 728	}
 729
 730	if len(includes) == 0 {
 731		includes = []string{""}
 732	}
 733
 734	p, cancel := p.WithCancel()
 735	match := genRegMatcher(includes, excludes)
 736	waitList := map[proto.NetworkRequestID]string{}
 737	idleCounter := utils.NewIdleCounter(d)
 738	update := p.tryTraceReq(includes, excludes)
 739	update(nil)
 740
 741	checkDone := func(id proto.NetworkRequestID) {
 742		if _, has := waitList[id]; has {
 743			delete(waitList, id)
 744			update(waitList)
 745			idleCounter.Done()
 746		}
 747	}
 748
 749	wait := p.EachEvent(func(sent *proto.NetworkRequestWillBeSent) {
 750		for _, t := range excludeTypes {
 751			if sent.Type == t {
 752				return
 753			}
 754		}
 755
 756		if match(sent.Request.URL) {
 757			// Redirect will send multiple NetworkRequestWillBeSent events with the same RequestID,
 758			// we should filter them out.
 759			if _, has := waitList[sent.RequestID]; !has {
 760				waitList[sent.RequestID] = sent.Request.URL
 761				update(waitList)
 762				idleCounter.Add()
 763			}
 764		}
 765	}, func(e *proto.NetworkLoadingFinished) {
 766		checkDone(e.RequestID)
 767	}, func(e *proto.NetworkLoadingFailed) {
 768		checkDone(e.RequestID)
 769	})
 770
 771	return func() {
 772		go func() {
 773			idleCounter.Wait(p.ctx)
 774			cancel()
 775		}()
 776		wait()
 777	}
 778}
 779
 780// WaitDOMStable waits until the change of the DOM tree is less or equal than diff percent for d duration.
 781// Be careful, d is not the max wait timeout, it's the least stable time.
 782// If you want to set a timeout you can use the [Page.Timeout] function.
 783func (p *Page) WaitDOMStable(d time.Duration, diff float64) error {
 784	defer p.tryTrace(TraceTypeWait, "dom-stable")()
 785
 786	domSnapshot, err := p.CaptureDOMSnapshot()
 787	if err != nil {
 788		return err
 789	}
 790
 791	t := time.NewTicker(d)
 792	defer t.Stop()
 793
 794	for {
 795		select {
 796		case <-t.C:
 797		case <-p.ctx.Done():
 798			return p.ctx.Err()
 799		}
 800
 801		currentDomSnapshot, err := p.CaptureDOMSnapshot()
 802		if err != nil {
 803			return err
 804		}
 805
 806		xs := lcs.NewWords(domSnapshot.Strings)
 807		ys := lcs.NewWords(currentDomSnapshot.Strings)
 808		lcs := xs.YadLCS(p.ctx, ys)
 809
 810		df := 1 - float64(len(lcs))/float64(len(ys))
 811		if df <= diff {
 812			break
 813		}
 814
 815		domSnapshot = currentDomSnapshot
 816	}
 817	return nil
 818}
 819
 820// WaitStable waits until the page is stable for d duration.
 821func (p *Page) WaitStable(d time.Duration) error {
 822	defer p.tryTrace(TraceTypeWait, "stable")()
 823
 824	var err error
 825
 826	setErr := sync.Once{}
 827
 828	utils.All(func() {
 829		e := p.WaitLoad()
 830		setErr.Do(func() { err = e })
 831	}, func() {
 832		p.WaitRequestIdle(d, nil, nil, nil)()
 833	}, func() {
 834		e := p.WaitDOMStable(d, 0)
 835		setErr.Do(func() { err = e })
 836	})()
 837
 838	return err
 839}
 840
 841// WaitIdle waits until the next window.requestIdleCallback is called.
 842func (p *Page) WaitIdle(timeout time.Duration) (err error) {
 843	_, err = p.Evaluate(evalHelper(js.WaitIdle, timeout.Milliseconds()).ByPromise())
 844	return err
 845}
 846
 847// WaitRepaint waits until the next repaint.
 848// Doc: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
 849func (p *Page) WaitRepaint() error {
 850	// we use root here because iframe doesn't trigger requestAnimationFrame
 851	_, err := p.root.Eval(`() => new Promise(r => requestAnimationFrame(r))`)
 852	return err
 853}
 854
 855// WaitLoad waits for the `window.onload` event, it returns immediately if the event is already fired.
 856func (p *Page) WaitLoad() error {
 857	defer p.tryTrace(TraceTypeWait, "load")()
 858	_, err := p.Evaluate(evalHelper(js.WaitLoad).ByPromise())
 859	return err
 860}
 861
 862// AddScriptTag to page. If url is empty, content will be used.
 863func (p *Page) AddScriptTag(url, content string) error {
 864	hash := md5.Sum([]byte(url + content))
 865	id := hex.EncodeToString(hash[:])
 866	_, err := p.Evaluate(evalHelper(js.AddScriptTag, id, url, content).ByPromise())
 867	return err
 868}
 869
 870// AddStyleTag to page. If url is empty, content will be used.
 871func (p *Page) AddStyleTag(url, content string) error {
 872	hash := md5.Sum([]byte(url + content))
 873	id := hex.EncodeToString(hash[:])
 874	_, err := p.Evaluate(evalHelper(js.AddStyleTag, id, url, content).ByPromise())
 875	return err
 876}
 877
 878// EvalOnNewDocument Evaluates given script in every frame upon creation (before loading frame's scripts).
 879func (p *Page) EvalOnNewDocument(js string) (remove func() error, err error) {
 880	res, err := proto.PageAddScriptToEvaluateOnNewDocument{Source: js}.Call(p)
 881	if err != nil {
 882		return
 883	}
 884
 885	remove = func() error {
 886		return proto.PageRemoveScriptToEvaluateOnNewDocument{
 887			Identifier: res.Identifier,
 888		}.Call(p)
 889	}
 890
 891	return
 892}
 893
 894// Wait until the js returns true.
 895func (p *Page) Wait(opts *EvalOptions) error {
 896	return utils.Retry(p.ctx, p.sleeper(), func() (bool, error) {
 897		res, err := p.Evaluate(opts)
 898		if err != nil {
 899			return true, err
 900		}
 901
 902		return res.Value.Bool(), nil
 903	})
 904}
 905
 906// WaitElementsMoreThan waits until there are more than num elements that match the selector.
 907func (p *Page) WaitElementsMoreThan(selector string, num int) error {
 908	return p.Wait(Eval(`(s, n) => document.querySelectorAll(s).length > n`, selector, num))
 909}
 910
 911// ObjectToJSON by object id.
 912func (p *Page) ObjectToJSON(obj *proto.RuntimeRemoteObject) (gson.JSON, error) {
 913	if obj.ObjectID == "" {
 914		return obj.Value, nil
 915	}
 916
 917	res, err := proto.RuntimeCallFunctionOn{
 918		ObjectID:            obj.ObjectID,
 919		FunctionDeclaration: `function() { return this }`,
 920		ReturnByValue:       true,
 921	}.Call(p)
 922	if err != nil {
 923		return gson.New(nil), err
 924	}
 925	return res.Result.Value, nil
 926}
 927
 928// ElementFromObject creates an Element from the remote object id.
 929func (p *Page) ElementFromObject(obj *proto.RuntimeRemoteObject) (*Element, error) {
 930	// If the element is in an iframe, we need the jsCtxID to inject helper.js to the correct context.
 931	id, err := p.jsCtxIDByObjectID(obj.ObjectID)
 932	if err != nil {
 933		return nil, err
 934	}
 935
 936	pid, err := p.getJSCtxID()
 937	if err != nil {
 938		return nil, err
 939	}
 940
 941	if id != pid {
 942		clone := *p
 943		clone.jsCtxID = &id
 944		p = &clone
 945	}
 946
 947	return &Element{
 948		e:       p.e,
 949		ctx:     p.ctx,
 950		sleeper: p.sleeper,
 951		page:    p,
 952		Object:  obj,
 953	}, nil
 954}
 955
 956// ElementFromNode creates an Element from the node, [proto.DOMNodeID] or [proto.DOMBackendNodeID] must be specified.
 957func (p *Page) ElementFromNode(node *proto.DOMNode) (*Element, error) {
 958	res, err := proto.DOMResolveNode{
 959		NodeID:        node.NodeID,
 960		BackendNodeID: node.BackendNodeID,
 961	}.Call(p)
 962	if err != nil {
 963		return nil, err
 964	}
 965
 966	el, err := p.ElementFromObject(res.Object)
 967	if err != nil {
 968		return nil, err
 969	}
 970
 971	// make sure always return an element node
 972	desc, err := el.Describe(0, false)
 973	if err != nil {
 974		return nil, err
 975	}
 976	if desc.NodeName == "#text" {
 977		el, err = el.Parent()
 978		if err != nil {
 979			return nil, err
 980		}
 981	}
 982
 983	return el, nil
 984}
 985
 986// ElementFromPoint creates an Element from the absolute point on the page.
 987// The point should include the window scroll offset.
 988func (p *Page) ElementFromPoint(x, y int) (*Element, error) {
 989	node, err := proto.DOMGetNodeForLocation{X: x, Y: y}.Call(p)
 990	if err != nil {
 991		return nil, err
 992	}
 993
 994	return p.ElementFromNode(&proto.DOMNode{
 995		BackendNodeID: node.BackendNodeID,
 996	})
 997}
 998
 999// Release the remote object. Usually, you don't need to call it.
1000// When a page is closed or reloaded, all remote objects will be released automatically.
1001// It's useful if the page never closes or reloads.
1002func (p *Page) Release(obj *proto.RuntimeRemoteObject) error {
1003	err := proto.RuntimeReleaseObject{ObjectID: obj.ObjectID}.Call(p)
1004	return err
1005}
1006
1007// Call implements the [proto.Client].
1008func (p *Page) Call(ctx context.Context, sessionID, methodName string, params interface{}) (res []byte, err error) {
1009	return p.browser.Call(ctx, sessionID, methodName, params)
1010}
1011
1012// Event of the page.
1013func (p *Page) Event() <-chan *Message {
1014	dst := make(chan *Message)
1015	s := p.event.Subscribe(p.ctx)
1016
1017	go func() {
1018		defer close(dst)
1019		for {
1020			select {
1021			case <-p.ctx.Done():
1022				return
1023			case msg, ok := <-s:
1024				if !ok {
1025					return
1026				}
1027				select {
1028				case <-p.ctx.Done():
1029					return
1030				case dst <- msg.(*Message): //nolint: forcetypeassert
1031				}
1032			}
1033		}
1034	}()
1035
1036	return dst
1037}
1038
1039func (p *Page) initEvents() {
1040	p.event = goob.New(p.ctx)
1041	event := p.browser.Context(p.ctx).Event()
1042
1043	go func() {
1044		for msg := range event {
1045			detached := proto.TargetDetachedFromTarget{}
1046			destroyed := proto.TargetTargetDestroyed{}
1047
1048			if (msg.Load(&detached) && detached.SessionID == p.SessionID) ||
1049				(msg.Load(destroyed) && destroyed.TargetID == p.TargetID) {
1050				p.sessionCancel()
1051				return
1052			}
1053
1054			if msg.SessionID != p.SessionID {
1055				continue
1056			}
1057
1058			p.event.Publish(msg)
1059		}
1060	}()
1061}