1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//! Browser document acquisition and element access.
use super::{WebClipboard, WebDocument, WebElement, clipboard};
use std::io;
use wasm_bindgen::JsCast;
use web_sys::Window;
impl WebDocument {
/// Obtains the document for the current browser window.
///
/// # Errors
/// Returns [`io::ErrorKind::Unsupported`] when no browser window or
/// document is available.
pub fn current() -> io::Result<Self> {
let window = web_sys::window().ok_or_else(|| {
io::Error::new(
io::ErrorKind::Unsupported,
"DOM access requires a browser Window",
)
})?;
Self::from_window(window)
}
/// Wraps a browser window's document.
///
/// # Errors
/// Returns [`io::ErrorKind::Unsupported`] when the window has no document.
pub fn from_window(window: Window) -> io::Result<Self> {
window
.document()
.map(|document| Self { document })
.ok_or_else(|| {
io::Error::new(io::ErrorKind::Unsupported, "Browser Window has no Document")
})
}
/// Returns the document body.
///
/// # Errors
/// Returns [`io::ErrorKind::NotFound`] before the document body exists.
pub fn body(&self) -> io::Result<WebElement> {
self.document
.body()
.map(|body| WebElement {
element: body.unchecked_into(),
})
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Document body is absent"))
}
/// Finds an element by its stable identifier.
#[must_use]
pub fn get_element_by_id(&self, id: &str) -> Option<WebElement> {
self.document
.get_element_by_id(id)
.map(|element| WebElement { element })
}
/// Creates an element with the supplied HTML tag name.
///
/// # Errors
/// Returns the browser's DOM validation error as [`io::ErrorKind::InvalidInput`].
pub fn create_element(&self, tag: &str) -> io::Result<WebElement> {
self.document
.create_element(tag)
.map(|element| WebElement { element })
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "Invalid DOM element name"))
}
/// Returns the browser's text clipboard provider.
///
/// Clipboard access is available only in a secure browser context and
/// remains subject to the browser's permission and user-activation
/// policy. The provider never exposes a filesystem or native clipboard
/// handle to the application.
///
/// # Errors
/// Returns [`io::ErrorKind::Unsupported`] when the current document has no
/// navigator clipboard API, including an insecure browser context.
pub fn clipboard(&self) -> io::Result<WebClipboard> {
clipboard::from_document(self)
}
}