playwright/api/selectors.rs
1use crate::imp::{core::*, prelude::*, selectors::Selectors as Impl};
2
3/// Selectors can be used to install custom selector engines.
4#[derive(Debug, Clone)]
5pub struct Selectors {
6 inner: Weak<Impl>
7}
8
9impl Selectors {
10 pub(crate) fn new(inner: Weak<Impl>) -> Self { Self { inner } }
11
12 /// An example of registering selector engine that queries elements based on a tag name:
13 ///
14 /// ```js
15 /// const { selectors, firefox } = require('playwright'); // Or 'chromium' or 'webkit'.
16 ///
17 /// (async () => {
18 /// // Must be a function that evaluates to a selector engine instance.
19 /// const createTagNameEngine = () => ({
20 /// // Returns the first element matching given selector in the root's subtree.
21 /// query(root, selector) {
22 /// return root.querySelector(selector);
23 /// },
24 ///
25 /// // Returns all elements matching given selector in the root's subtree.
26 /// queryAll(root, selector) {
27 /// return Array.from(root.querySelectorAll(selector));
28 /// }
29 /// });
30 ///
31 /// // Register the engine. Selectors will be prefixed with "tag=".
32 /// await selectors.register('tag', createTagNameEngine);
33 ///
34 /// const browser = await firefox.launch();
35 /// const page = await browser.newPage();
36 /// await page.setContent(`<div><button>Click me</button></div>`);
37 ///
38 /// // Use the selector prefixed with its name.
39 /// const button = await page.$('tag=button');
40 /// // Combine it with other selector engines.
41 /// await page.click('tag=div >> text="Click me"');
42 /// // Can use it in any methods supporting selectors.
43 /// const buttonCount = await page.$$eval('tag=button', buttons => buttons.length);
44 ///
45 /// await browser.close();
46 /// })();
47 /// ```
48 /// # Args
49 /// ## name
50 /// Name that is used in selectors as a prefix, e.g. `{name: 'foo'}` enables `foo=myselectorbody` selectors.
51 /// May only contain `[a-zA-Z0-9_]` characters.
52 /// ## script
53 /// Script that evaluates to a selector engine instance.
54 /// ## content_script
55 /// Whether to run this selector engine in isolated JavaScript environment. This environment
56 /// has access to the same DOM, but not any JavaScript objects from the frame's scripts.
57 /// Defaults to `false`. Note that running as a content script is not
58 /// guaranteed when this engine is used together with other registered engines.
59 pub async fn register(
60 &self,
61 name: &str,
62 script: &str,
63 content_script: bool
64 ) -> Result<(), Arc<Error>> {
65 let inner = upgrade(&self.inner)?;
66 inner.register(name, script, content_script).await
67 }
68}