Struct headless_chrome::util::Wait

source ·
pub struct Wait { /* private fields */ }
Expand description

A helper to wait until some event has passed.

Implementations§

Examples found in repository?
src/browser/transport/mod.rs (line 174)
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
    pub fn call_method<C>(
        &self,
        method: C,
        destination: MethodDestination,
    ) -> Result<C::ReturnObject>
    where
        C: Method + serde::Serialize,
    {
        // TODO: use get_mut to get exclusive access for entire block... maybe.
        if !self.open.load(Ordering::SeqCst) {
            return Err(ConnectionClosed {}.into());
        }
        let call_id = self.unique_call_id();
        let call = method.to_method_call(call_id);

        let message_text = serde_json::to_string(&call)?;

        let response_rx = self.waiting_call_registry.register_call(call.id);

        match destination {
            MethodDestination::Target(session_id) => {
                let message = message_text.clone();
                let target_method = Target::SendMessageToTarget {
                    target_id: None,
                    session_id: Some(session_id.0),
                    message: message,
                };
                let mut raw = message_text.clone();
                raw.truncate(300);
                trace!("Msg to tab: {}", &raw);
                if let Err(e) = self.call_method_on_browser(target_method) {
                    warn!("Failed to call method on browser: {:?}", e);
                    self.waiting_call_registry.unregister_call(call.id);
                    trace!("Unregistered callback: {:?}", call.id);
                    return Err(e);
                }
            }
            MethodDestination::Browser => {
                if let Err(e) = self.web_socket_connection.send_message(&message_text) {
                    self.waiting_call_registry.unregister_call(call.id);
                    return Err(e);
                }
                trace!("sent method call to browser via websocket");
            }
        }

        let mut params_string = format!("{:?}", call.get_params());
        params_string.truncate(400);
        trace!(
            "waiting for response from call registry: {} {:?}",
            &call_id,
            params_string
        );

        let response_result = util::Wait::new(self.idle_browser_timeout, Duration::from_millis(5))
            .until(|| response_rx.try_recv().ok());
        trace!("received response for: {} {:?}", &call_id, params_string);
        parse_response::<C::ReturnObject>((response_result?)?)
    }
Examples found in repository?
src/browser/mod.rs (line 194)
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
    pub fn wait_for_initial_tab(&self) -> Result<Arc<Tab>> {
        util::Wait::with_timeout(Duration::from_secs(10))
            .until(|| self.inner.tabs.lock().unwrap().first().map(|tab| Arc::clone(tab)))
            .map_err(Into::into)
    }

    /// Create a new tab and return a handle to it.
    ///
    /// If you want to specify its starting options, see `new_tab_with_options`.
    ///
    /// ```rust
    /// # use anyhow::Result;
    /// # fn main() -> Result<()> {
    /// #
    /// # use headless_chrome::Browser;
    /// # let browser = Browser::default()?;
    /// let first_tab = browser.wait_for_initial_tab()?;
    /// let new_tab = browser.new_tab()?;
    /// let num_tabs = browser.get_tabs().lock().unwrap().len();
    /// assert_eq!(2, num_tabs);
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_tab(&self) -> Result<Arc<Tab>> {
        let default_blank_tab = CreateTarget {
            url: "about:blank".to_string(),
            width: None,
            height: None,
            browser_context_id: None,
            enable_begin_frame_control: None,
            new_window: None,
            background: None,
        };
        self.new_tab_with_options(default_blank_tab)
    }

    /// Create a new tab with a starting url, height / width, context ID and 'frame control'
    /// ```rust
    /// # use anyhow::Result;
    /// # fn main() -> Result<()> {
    /// #
    /// # use headless_chrome::{Browser, protocol::target::methods::CreateTarget};
    /// # let browser = Browser::default()?;
    ///    let new_tab = browser.new_tab_with_options(CreateTarget {
    ///    url: "chrome://version",
    ///    width: Some(1024),
    ///    height: Some(800),
    ///    browser_context_id: None,
    ///    enable_begin_frame_control: None,
    ///    })?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_tab_with_options(&self, create_target_params: CreateTarget) -> Result<Arc<Tab>> {
        let target_id = self.call_method(create_target_params)?.target_id;

        util::Wait::with_timeout(Duration::from_secs(20))
            .until(|| {
                let tabs = self.inner.tabs.lock().unwrap();
                tabs.iter().find_map(|tab| {
                    if *tab.get_target_id() == target_id {
                        Some(tab.clone())
                    } else {
                        None
                    }
                })
            })
            .map_err(Into::into)
    }
More examples
Hide additional examples
src/browser/tab/element/mod.rs (line 235)
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
    pub fn wait_for_element_with_custom_timeout(
        &self,
        selector: &str,
        timeout: std::time::Duration,
    ) -> Result<Element<'_>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(timeout).strict_until(
            || self.find_element(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_xpath_with_custom_timeout(
        &self,
        selector: &str,
        timeout: std::time::Duration,
    ) -> Result<Element<'_>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(timeout).strict_until(
            || self.find_element_by_xpath(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_elements(&self, selector: &str) -> Result<Vec<Element<'_>>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(Duration::from_secs(3)).strict_until(
            || self.find_elements(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_elements_by_xpath(&self, selector: &str) -> Result<Vec<Element<'_>>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(Duration::from_secs(3)).strict_until(
            || self.find_elements_by_xpath(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    /// Moves the mouse to the middle of this element
    pub fn move_mouse_over(&self) -> Result<&Self> {
        self.scroll_into_view()?;
        let midpoint = self.get_midpoint()?;
        self.parent.move_mouse_to_point(midpoint)?;
        Ok(self)
    }

    pub fn click(&self) -> Result<&Self> {
        self.scroll_into_view()?;
        debug!("Clicking element {:?}", &self);

        self.call_js_fn("function() { this.click(); return 1; }", vec![], false)?
            .value.unwrap();


        /* let midpoint = self.get_midpoint()?;
        self.parent.click_point(midpoint)?; */
        if let Err(_) = self.parent.wait_until_navigated() {
            info!("[CLICK] Page load timeout..");
        }
        
        // MUST reload DOM in case page refreshed..
        self.parent.load_document();

        Ok(self)
    }

    pub fn type_into(&self, text: &str) -> Result<&Self> {
        self.click()?;

        debug!("Typing into element ( {:?} ): {}", &self, text);

        self.parent.type_str(text)?;

        Ok(self)
    }

    pub fn call_js_fn(
        &self,
        function_declaration: &str,
        args: Vec<serde_json::Value>,
        await_promise: bool,
    ) -> Result<Runtime::RemoteObject> {
        let mut args = args.clone();
        let result = self
            .parent
            .call_method(Runtime::CallFunctionOn {
                object_id: Some(self.remote_object_id.clone()),
                function_declaration: function_declaration.to_string(),
                arguments: args
                    .iter_mut()
                    .map(|v| {
                        Some(Runtime::CallArgument {
                            value: Some(v.take()),
                            unserializable_value: None,
                            object_id: None,
                        })
                    })
                    .collect(),
                return_by_value: Some(false),
                generate_preview: Some(true),
                silent: Some(false),
                await_promise: Some(await_promise),
                user_gesture: None,
                execution_context_id: None,
                object_group: None,
                throw_on_side_effect: None,
            })?
            .result;

        Ok(result)
    }

    pub fn focus(&self) -> Result<&Self> {
        self.scroll_into_view()?;
        self.parent.call_method(DOM::Focus {
            backend_node_id: Some(self.backend_node_id),
            node_id: None,
            object_id: None,
        })?;
        Ok(self)
    }

    /// Returns the inner text of an HTML Element. Returns an empty string on elements with no text.
    ///
    /// Note: .innerText and .textContent are not the same thing. See:
    /// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
    ///
    /// Note: if you somehow call this on a node that's not an HTML Element (e.g. `document`), this
    /// will fail.
    /// ```rust
    /// # use anyhow::Result;
    /// # fn main() -> Result<()> {
    /// #
    /// use headless_chrome::Browser;
    /// use std::time::Duration;
    /// let browser = Browser::default()?;
    /// let url = "https://web.archive.org/web/20190403224553/https://en.wikipedia.org/wiki/JavaScript";
    /// let inner_text_content = browser.wait_for_initial_tab()?
    ///     .navigate_to(url)?
    ///     .wait_for_element_with_custom_timeout("#Misplaced_trust_in_developers", Duration::from_secs(10))?
    ///     .get_inner_text()?;
    /// assert_eq!(inner_text_content, "Misplaced trust in developers");
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_inner_text(&self) -> Result<String> {
        let text: String = serde_json::from_value(
            self.call_js_fn("function() { return this.innerText }", vec![], false)?
                .value
                .unwrap(),
        )?;
        Ok(text)
    }

    /// Get the full HTML contents of the element.
    /// 
    /// Equivalent to the following JS: ```element.outerHTML```.
    pub fn get_content(&self) -> Result<String> {
        let html = self.
                call_js_fn("function() { return this.outerHTML }", vec![], false)?
                    .value
                    .unwrap();

        Ok(String::from(html.as_str().unwrap()))
    }

    pub fn get_computed_styles(&self) -> Result<Vec<CSSComputedStyleProperty>> {
        let styles = self
            .parent
            .call_method(CSS::GetComputedStyleForNode {
                node_id: self.node_id,
            })?
            .computed_style;

        Ok(styles)
    }

    pub fn get_description(&self) -> Result<DOM::Node> {
        let node = self
            .parent
            .call_method(DOM::DescribeNode {
                node_id: None,
                backend_node_id: Some(self.backend_node_id),
                depth: None,
                object_id: None,
                pierce: None,
            })?
            .node;
        Ok(node)
    }

    /// Capture a screenshot of this element.
    ///
    /// The screenshot is taken from the surface using this element's content-box.
    ///
    /// ```rust,no_run
    /// # use anyhow::Result;
    /// # fn main() -> Result<()> {
    /// #
    /// use headless_chrome::{protocol::page::ScreenshotFormat, Browser};
    /// let browser = Browser::default()?;
    /// let png_data = browser.wait_for_initial_tab()?
    ///     .navigate_to("https://en.wikipedia.org/wiki/WebKit")?
    ///     .wait_for_element("#mw-content-text > div > table.infobox.vevent")?
    ///     .capture_screenshot(ScreenshotFormat::PNG)?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn capture_screenshot(
        &self,
        format: Page::CaptureScreenshotFormatOption,
    ) -> Result<Vec<u8>> {
        self.scroll_into_view()?;
        self.parent.capture_screenshot(
            format,
            Some(90),
            Some(self.get_box_model()?.content_viewport()),
            true,
        )
    }

    pub fn set_input_files(&self, file_paths: &[&str]) -> Result<&Self> {
        self.parent.call_method(DOM::SetFileInputFiles {
            files: file_paths.to_vec().iter().map(|v| v.to_string()).collect(),
            backend_node_id: Some(self.backend_node_id),
            node_id: None,
            object_id: None,
        })?;
        Ok(self)
    }

    /// Scrolls the current element into view
    ///
    /// Used prior to any action applied to the current element to ensure action is duable.
    pub fn scroll_into_view(&self) -> Result<&Self> {
        let result = self.call_js_fn(
            "async function() {
                if (!this.isConnected)
                    return 'Node is detached from document';
                if (this.nodeType !== Node.ELEMENT_NODE)
                    return 'Node is not of type HTMLElement';

                const visibleRatio = await new Promise(resolve => {
                    const observer = new IntersectionObserver(entries => {
                        resolve(entries[0].intersectionRatio);
                        observer.disconnect();
                    });
                    observer.observe(this);
                });

                if (visibleRatio !== 1.0)
                    this.scrollIntoView({
                        block: 'center',
                        inline: 'center',
                        behavior: 'instant'
                    });
                return false;
            }",
            vec![],
            true,
        )?;

        if result.Type == Runtime::RemoteObjectType::String {
            let error_text = result.value.unwrap().as_str().unwrap().to_string();
            return Err(ScrollFailed { error_text }.into());
        }

        Ok(self)
    }


    pub fn get_attributes(&self) -> Result<HashMap<String, String>> {
        // https://chromedevtools.github.io/devtools-protocol/tot/DOM/#method-getAttributes

        let mut attrs_map: HashMap<String, String> = HashMap::default();

        /* let attrs = self.parent
            .call_method(DOM::GetAttributes {
                node_id: self.node_id
            })?.attributes; */
        let node = self.get_description().unwrap(); //.local_name;
        
        
        let attrs = node.attributes.unwrap_or(vec![]);
        let tag = node.local_name;

        attrs_map.insert("tag".to_string(), tag);
        attrs_map.insert("value".to_string(), node.value.unwrap_or("".to_string()));
        for i in (0..attrs.len() - 1).step_by(2) {

            let k = attrs[i].to_string();
            let v = attrs[i+1].to_string();
            attrs_map.insert(k, v);
        }

        Ok(attrs_map)
    }

    /* pub fn get_attributes(&self) -> Result<Option<Vec<String>>> {
        let description = self.get_description()?;
        Ok(description.attributes)
    } */

    /// Get boxes for this element
    pub fn get_box_model(&self) -> Result<BoxModel> {
        let model = self
            .parent
            .call_method(DOM::GetBoxModel {
                node_id: None,
                backend_node_id: Some(self.backend_node_id),
                object_id: None,
            })?
            .model;
        Ok(BoxModel {
            content: ElementQuad::from_raw_points(&model.content),
            padding: ElementQuad::from_raw_points(&model.padding),
            border: ElementQuad::from_raw_points(&model.border),
            margin: ElementQuad::from_raw_points(&model.margin),
            width: model.width as f64,
            height: model.height as f64,
        })
    }

    pub fn get_midpoint(&self) -> Result<Point> {
        match self
            .parent
            .call_method(DOM::GetContentQuads {
                node_id: None,
                backend_node_id: Some(self.backend_node_id),
                object_id: None,
            })
            .and_then(|quad| {
                let raw_quad = quad.quads.first().unwrap();
                let input_quad = ElementQuad::from_raw_points(&raw_quad);

                Ok((input_quad.bottom_right + input_quad.top_left) / 2.0)
            }) {
            Ok(e) => return Ok(e),
            Err(_) => {
                let mut p = Point { x: 0.0, y: 0.0 };

                p = util::Wait::with_timeout(Duration::from_secs(20)).until(|| {
                    let r = self
                        .call_js_fn(
                            r#"
                    function() {
                        let rect = this.getBoundingClientRect();

                        if(rect.x != 0) {
                            this.scrollIntoView();
                        }

                        return this.getBoundingClientRect();
                    }
                    "#,
                            vec![],
                            false,
                        )
                        .unwrap();

                    let res = util::extract_midpoint(r);

                    match res {
                        Ok(v) => {
                            if v.x != 0.0 {
                                Some(v)
                            } else {
                                None
                            }
                        }
                        _ => None,
                    }
                })?;

                return Ok(p);
            }
        }
    }
src/browser/tab/mod.rs (line 536)
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
    pub fn wait_until_navigated(&self) -> Result<&Self> {
        let navigating = Arc::clone(&self.navigating);
        let timeout = *self.default_timeout.read().unwrap();

        util::Wait::with_timeout(timeout).until(|| {
            if navigating.load(Ordering::SeqCst) {
                None
            } else {
                Some(true)
            }
        })?;
        debug!("A tab finished navigating");

        Ok(self)
    }

    // Pulls focus to this tab
    pub fn bring_to_front(&self) -> Result<Page::BringToFrontReturnObject> {
        Ok(self.call_method(Page::BringToFront(None))?)
    }

    pub fn navigate_to(&self, url: &str) -> Result<&Self> {
        let return_object = self.call_method(Navigate {
            url: url.to_string(),
            referrer: None,
            transition_Type: None,
            frame_id: None,
            referrer_policy: None,
        })?;
        if let Some(error_text) = return_object.error_text {
            return Err(NavigationFailed { error_text }.into());
        }

        let navigating = Arc::clone(&self.navigating);
        navigating.store(true, Ordering::SeqCst);

        info!("Navigating a tab to {}", url);
        self.wait_until_navigated().unwrap();
        
        self.load_document();
        Ok(self)
    }

    /// Set default timeout for the tab
    ///
    /// This will be applied to all [wait_for_element](Tab::wait_for_element) and [wait_for_elements](Tab::wait_for_elements) calls for this tab
    ///
    /// ```rust
    /// # use anyhow::Result;
    /// # fn main() -> Result<()> {
    /// # use headless_chrome::Browser;
    /// # let browser = Browser::default()?;
    /// let tab = browser.wait_for_initial_tab()?;
    /// tab.set_default_timeout(std::time::Duration::from_secs(5));
    /// #
    /// # Ok(())
    /// # }

    /// ```
    pub fn set_default_timeout(&self, timeout: Duration) -> &Self {
        let mut current_timeout = self.default_timeout.write().unwrap();
        *current_timeout = timeout;
        &self
    }

    /// Analogous to Puppeteer's ['slowMo' option](https://github.com/GoogleChrome/puppeteer/blob/v1.20.0/docs/api.md#puppeteerconnectoptions),
    /// but with some differences:
    ///
    /// * It doesn't add a delay after literally every message sent via the protocol, but instead
    ///   just for:
    ///     * clicking a specific point on the page (default: 100ms before moving the mouse, 250ms
    ///       before pressing and releasting mouse button)
    ///     * pressing a key (default: 25 ms)
    ///     * reloading the page (default: 100ms)
    ///     * closing a tab (default: 100ms)
    /// * Instead of an absolute number of milliseconds, it's a multiplier, so that we can delay
    ///   longer on certain actions like clicking or moving the mouse, and shorter on others like
    ///   on pressing a key (or the individual 'mouseDown' and 'mouseUp' actions that go across the
    ///   wire. If the delay was always the same, filling out a form (e.g.) would take ages).
    ///
    /// By default the multiplier is set to zero, which effectively disables the slow motion.
    ///
    /// The defaults for the various actions (i.e. how long we sleep for when
    /// multiplier is 1.0) are supposed to be just slow enough to help a human see what's going on
    /// as a test runs.
    pub fn set_slow_motion_multiplier(&self, multiplier: f64) -> &Self {
        let mut slow_motion_multiplier = self.slow_motion_multiplier.write().unwrap();
        *slow_motion_multiplier = multiplier;
        &self
    }

    fn optional_slow_motion_sleep(&self, millis: u64) {
        let multiplier = self.slow_motion_multiplier.read().unwrap();
        #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
        let scaled_millis = millis * *multiplier as u64;
        sleep(Duration::from_millis(scaled_millis));
    }

    pub fn wait_for_element(&self, selector: &str) -> Result<Element<'_>> {
        let t = self.default_timeout.read().unwrap().clone();
        self.wait_for_element_with_custom_timeout(selector, t)
    }

    pub fn wait_for_xpath(&self, selector: &str) -> Result<Element<'_>> {
        self.wait_for_xpath_with_custom_timeout(selector, *self.default_timeout.read().unwrap())
    }

    pub fn wait_for_element_with_custom_timeout(
        &self,
        selector: &str,
        timeout: std::time::Duration,
    ) -> Result<Element<'_>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(timeout).strict_until(
             || self.find_element(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_xpath_with_custom_timeout(
        &self,
        selector: &str,
        timeout: std::time::Duration,
    ) -> Result<Element<'_>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(timeout).strict_until(
            || self.find_element_by_xpath(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_elements(&self, selector: &str) -> Result<Vec<Element<'_>>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(*self.default_timeout.read().unwrap()).strict_until(
            || self.find_elements(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_elements_by_xpath(&self, selector: &str) -> Result<Vec<Element<'_>>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(*self.default_timeout.read().unwrap()).strict_until(
            || self.find_elements_by_xpath(selector),
            Error::downcast::<NoElementFound>,
        )
    }
src/browser/process.rs (line 452)
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
    fn ws_url_from_output(child_process: &mut Child) -> Result<Url> {
        let chrome_output_result = util::Wait::with_timeout(Duration::from_secs(30)).until(|| {
            let my_stderr = BufReader::new(child_process.stderr.as_mut().unwrap());
            match Self::ws_url_from_reader(my_stderr) {
                Ok(output_option) => {
                    if let Some(output) = output_option {
                        Some(Ok(output))
                    } else {
                        None
                    }
                }
                Err(err) => Some(Err(err)),
            }
        });

        if let Ok(output_result) = chrome_output_result {

            Ok(Url::parse(&output_result?)?)
        } else {
            Err(ChromeLaunchError::PortOpenTimeout {}.into())
        }
    }

Wait until the given predicate returns Some(G) or timeout arrives.

Note: If your predicate function shadows potential unexpected errors you should consider using #strict_until.

Examples found in repository?
src/browser/mod.rs (line 195)
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
    pub fn wait_for_initial_tab(&self) -> Result<Arc<Tab>> {
        util::Wait::with_timeout(Duration::from_secs(10))
            .until(|| self.inner.tabs.lock().unwrap().first().map(|tab| Arc::clone(tab)))
            .map_err(Into::into)
    }

    /// Create a new tab and return a handle to it.
    ///
    /// If you want to specify its starting options, see `new_tab_with_options`.
    ///
    /// ```rust
    /// # use anyhow::Result;
    /// # fn main() -> Result<()> {
    /// #
    /// # use headless_chrome::Browser;
    /// # let browser = Browser::default()?;
    /// let first_tab = browser.wait_for_initial_tab()?;
    /// let new_tab = browser.new_tab()?;
    /// let num_tabs = browser.get_tabs().lock().unwrap().len();
    /// assert_eq!(2, num_tabs);
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_tab(&self) -> Result<Arc<Tab>> {
        let default_blank_tab = CreateTarget {
            url: "about:blank".to_string(),
            width: None,
            height: None,
            browser_context_id: None,
            enable_begin_frame_control: None,
            new_window: None,
            background: None,
        };
        self.new_tab_with_options(default_blank_tab)
    }

    /// Create a new tab with a starting url, height / width, context ID and 'frame control'
    /// ```rust
    /// # use anyhow::Result;
    /// # fn main() -> Result<()> {
    /// #
    /// # use headless_chrome::{Browser, protocol::target::methods::CreateTarget};
    /// # let browser = Browser::default()?;
    ///    let new_tab = browser.new_tab_with_options(CreateTarget {
    ///    url: "chrome://version",
    ///    width: Some(1024),
    ///    height: Some(800),
    ///    browser_context_id: None,
    ///    enable_begin_frame_control: None,
    ///    })?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_tab_with_options(&self, create_target_params: CreateTarget) -> Result<Arc<Tab>> {
        let target_id = self.call_method(create_target_params)?.target_id;

        util::Wait::with_timeout(Duration::from_secs(20))
            .until(|| {
                let tabs = self.inner.tabs.lock().unwrap();
                tabs.iter().find_map(|tab| {
                    if *tab.get_target_id() == target_id {
                        Some(tab.clone())
                    } else {
                        None
                    }
                })
            })
            .map_err(Into::into)
    }
More examples
Hide additional examples
src/browser/tab/mod.rs (lines 536-542)
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
    pub fn wait_until_navigated(&self) -> Result<&Self> {
        let navigating = Arc::clone(&self.navigating);
        let timeout = *self.default_timeout.read().unwrap();

        util::Wait::with_timeout(timeout).until(|| {
            if navigating.load(Ordering::SeqCst) {
                None
            } else {
                Some(true)
            }
        })?;
        debug!("A tab finished navigating");

        Ok(self)
    }
src/browser/process.rs (lines 452-464)
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
    fn ws_url_from_output(child_process: &mut Child) -> Result<Url> {
        let chrome_output_result = util::Wait::with_timeout(Duration::from_secs(30)).until(|| {
            let my_stderr = BufReader::new(child_process.stderr.as_mut().unwrap());
            match Self::ws_url_from_reader(my_stderr) {
                Ok(output_option) => {
                    if let Some(output) = output_option {
                        Some(Ok(output))
                    } else {
                        None
                    }
                }
                Err(err) => Some(Err(err)),
            }
        });

        if let Ok(output_result) = chrome_output_result {

            Ok(Url::parse(&output_result?)?)
        } else {
            Err(ChromeLaunchError::PortOpenTimeout {}.into())
        }
    }
src/browser/tab/element/mod.rs (lines 574-605)
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
    pub fn get_midpoint(&self) -> Result<Point> {
        match self
            .parent
            .call_method(DOM::GetContentQuads {
                node_id: None,
                backend_node_id: Some(self.backend_node_id),
                object_id: None,
            })
            .and_then(|quad| {
                let raw_quad = quad.quads.first().unwrap();
                let input_quad = ElementQuad::from_raw_points(&raw_quad);

                Ok((input_quad.bottom_right + input_quad.top_left) / 2.0)
            }) {
            Ok(e) => return Ok(e),
            Err(_) => {
                let mut p = Point { x: 0.0, y: 0.0 };

                p = util::Wait::with_timeout(Duration::from_secs(20)).until(|| {
                    let r = self
                        .call_js_fn(
                            r#"
                    function() {
                        let rect = this.getBoundingClientRect();

                        if(rect.x != 0) {
                            this.scrollIntoView();
                        }

                        return this.getBoundingClientRect();
                    }
                    "#,
                            vec![],
                            false,
                        )
                        .unwrap();

                    let res = util::extract_midpoint(r);

                    match res {
                        Ok(v) => {
                            if v.x != 0.0 {
                                Some(v)
                            } else {
                                None
                            }
                        }
                        _ => None,
                    }
                })?;

                return Ok(p);
            }
        }
    }
src/browser/transport/mod.rs (line 175)
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
    pub fn call_method<C>(
        &self,
        method: C,
        destination: MethodDestination,
    ) -> Result<C::ReturnObject>
    where
        C: Method + serde::Serialize,
    {
        // TODO: use get_mut to get exclusive access for entire block... maybe.
        if !self.open.load(Ordering::SeqCst) {
            return Err(ConnectionClosed {}.into());
        }
        let call_id = self.unique_call_id();
        let call = method.to_method_call(call_id);

        let message_text = serde_json::to_string(&call)?;

        let response_rx = self.waiting_call_registry.register_call(call.id);

        match destination {
            MethodDestination::Target(session_id) => {
                let message = message_text.clone();
                let target_method = Target::SendMessageToTarget {
                    target_id: None,
                    session_id: Some(session_id.0),
                    message: message,
                };
                let mut raw = message_text.clone();
                raw.truncate(300);
                trace!("Msg to tab: {}", &raw);
                if let Err(e) = self.call_method_on_browser(target_method) {
                    warn!("Failed to call method on browser: {:?}", e);
                    self.waiting_call_registry.unregister_call(call.id);
                    trace!("Unregistered callback: {:?}", call.id);
                    return Err(e);
                }
            }
            MethodDestination::Browser => {
                if let Err(e) = self.web_socket_connection.send_message(&message_text) {
                    self.waiting_call_registry.unregister_call(call.id);
                    return Err(e);
                }
                trace!("sent method call to browser via websocket");
            }
        }

        let mut params_string = format!("{:?}", call.get_params());
        params_string.truncate(400);
        trace!(
            "waiting for response from call registry: {} {:?}",
            &call_id,
            params_string
        );

        let response_result = util::Wait::new(self.idle_browser_timeout, Duration::from_millis(5))
            .until(|| response_rx.try_recv().ok());
        trace!("received response for: {} {:?}", &call_id, params_string);
        parse_response::<C::ReturnObject>((response_result?)?)
    }

Wait until the given predicate returns Ok(G), an unexpected error occurs or timeout arrives.

Errors produced by the predicate are downcasted by the additional provided closure. If the downcast is successful - the error is ignored, otherwise the wait is terminated and Err(error) containing the unexpected failure is returned to the caller.

You can use failure::Error::downcast::<YourStructName> out-of-the-box, if you need to ignore one expected error, or you can implement a matching closure that responds to multiple error types.

Examples found in repository?
src/browser/tab/element/mod.rs (lines 235-238)
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
    pub fn wait_for_element_with_custom_timeout(
        &self,
        selector: &str,
        timeout: std::time::Duration,
    ) -> Result<Element<'_>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(timeout).strict_until(
            || self.find_element(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_xpath_with_custom_timeout(
        &self,
        selector: &str,
        timeout: std::time::Duration,
    ) -> Result<Element<'_>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(timeout).strict_until(
            || self.find_element_by_xpath(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_elements(&self, selector: &str) -> Result<Vec<Element<'_>>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(Duration::from_secs(3)).strict_until(
            || self.find_elements(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_elements_by_xpath(&self, selector: &str) -> Result<Vec<Element<'_>>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(Duration::from_secs(3)).strict_until(
            || self.find_elements_by_xpath(selector),
            Error::downcast::<NoElementFound>,
        )
    }
More examples
Hide additional examples
src/browser/tab/mod.rs (lines 645-648)
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
    pub fn wait_for_element_with_custom_timeout(
        &self,
        selector: &str,
        timeout: std::time::Duration,
    ) -> Result<Element<'_>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(timeout).strict_until(
             || self.find_element(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_xpath_with_custom_timeout(
        &self,
        selector: &str,
        timeout: std::time::Duration,
    ) -> Result<Element<'_>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(timeout).strict_until(
            || self.find_element_by_xpath(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_elements(&self, selector: &str) -> Result<Vec<Element<'_>>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(*self.default_timeout.read().unwrap()).strict_until(
            || self.find_elements(selector),
            Error::downcast::<NoElementFound>,
        )
    }

    pub fn wait_for_elements_by_xpath(&self, selector: &str) -> Result<Vec<Element<'_>>> {
        debug!("Waiting for element with selector: {:?}", selector);
        util::Wait::with_timeout(*self.default_timeout.read().unwrap()).strict_until(
            || self.find_elements_by_xpath(selector),
            Error::downcast::<NoElementFound>,
        )
    }

Trait Implementations§

Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Get the TypeId of this object.