Module: Ferrum::Frame::DOM

Included in:
Ferrum::Frame
Defined in:
lib/ferrum/frame/dom.rb,
sig/ferrum/frame/dom.rbs

Overview

Evaluates and executes JavaScript to query and manipulate a frame's DOM: reading the URL, title, doctype, and HTML, finding nodes by XPath or CSS selector, and injecting <script>, <style>, and <link> tags.

Constant Summary collapse

WAIT_INTERVAL =

Returns:

  • (::Float)
0.05
SCRIPT_SRC_TAG =

Returns:

  • (::String)
<<~JS
  function(url, type) {
    const script = document.createElement("script");
    script.src = url;
    script.type = type;
    document.head.appendChild(script);
    return new Promise(resolve => script.onload = resolve);
  }
JS
SCRIPT_TEXT_TAG =

Returns:

  • (::String)
<<~JS
  function(content, type) {
    const script = document.createElement("script");
    script.text = content;
    script.type = type;
    document.head.appendChild(script);
  }
JS
STYLE_TAG =

Returns:

  • (::String)
<<~JS
  function(content) {
    const style = document.createElement("style");
    style.type = "text/css";
    style.appendChild(document.createTextNode(content));
    document.head.appendChild(style);
  }
JS
<<~JS
  function(url) {
    const link = document.createElement("link");
    link.rel = "stylesheet";
    link.href = url;
    document.head.appendChild(link);
    return new Promise(resolve => link.onload = resolve);
  }
JS

Instance Method Summary collapse

Instance Method Details

#add_script_tag(url: nil, path: nil, content: nil, type: "text/javascript") ⇒ Object

Adds a <script> tag to the document.

Examples:

browser.add_script_tag(url: "http://example.com/stylesheet.css") # => true

Parameters:

  • url (String, nil) (defaults to: nil)
  • path (String, nil) (defaults to: nil)
  • content (String, nil) (defaults to: nil)
  • type (String) (defaults to: "text/javascript")
  • url: (Object, nil) (defaults to: nil)
  • path: (Object, nil) (defaults to: nil)
  • content: (Object, nil) (defaults to: nil)
  • type: (::String) (defaults to: "text/javascript")

Returns:

  • (Object)

Raises:



340
341
342
343
344
345
346
347
348
349
350
351
352
# File 'lib/ferrum/frame/dom.rb', line 340

def add_script_tag(url: nil, path: nil, content: nil, type: "text/javascript")
  if url
    evaluate(SCRIPT_SRC_TAG, url, type)
  elsif path || content
    if path
      content = File.read(path)
      content += "\n//# sourceURL=#{path}"
    end
    evaluate(SCRIPT_TEXT_TAG, content, type)
  end

  true
end

#add_style_tag(url: nil, path: nil, content: nil) ⇒ Object

Adds a <style> tag to the document.

Examples:

browser.add_style_tag(content: "h1 { font-size: 40px; }") # => true

Parameters:

  • url (String, nil) (defaults to: nil)
  • path (String, nil) (defaults to: nil)
  • content (String, nil) (defaults to: nil)
  • url: (Object, nil) (defaults to: nil)
  • path: (Object, nil) (defaults to: nil)
  • content: (Object, nil) (defaults to: nil)

Returns:

  • (Object)

Raises:



368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/ferrum/frame/dom.rb', line 368

def add_style_tag(url: nil, path: nil, content: nil)
  if url
    evaluate(LINK_TAG, url)
  elsif path || content
    if path
      content = File.read(path)
      content += "\n//# sourceURL=#{path}"
    end
    evaluate(STYLE_TAG, content)
  end

  true
end

#at_css(selector, within: nil) ⇒ Node?

Finds a node by using a CSS path selector.

Examples:

browser.go_to("https://github.com/")
browser.at_css("a[aria-label='Issues you created']") # => Node

Parameters:

  • selector (String) —

    The CSS path selector.

  • within (Node, nil) (defaults to: nil) —

    The parent node to search within.

  • within: (Object, nil) (defaults to: nil)

Returns:

  • (Node, nil) —

    The matching node.

Raises:



229
230
231
232
233
234
235
236
237
238
# File 'lib/ferrum/frame/dom.rb', line 229

def at_css(selector, within: nil)
  expr = <<~JS
    function(selector, within) {
      within ||= document
      return within.querySelector(selector);
    }
  JS

  evaluate(expr, selector, within)
end

#at_xpath(selector, within: nil) ⇒ Node?

Finds a node by using a XPath selector.

Examples:

browser.go_to("https://github.com/")
browser.at_xpath("//a[@aria-label='Issues you created']") # => Node

Parameters:

  • selector (String) —

    The XPath selector.

  • within (Node, nil) (defaults to: nil) —

    The parent node to search within.

  • within: (Object, nil) (defaults to: nil)

Returns:

  • (Node, nil) —

    The matching node.

Raises:



171
172
173
174
175
176
177
178
179
180
# File 'lib/ferrum/frame/dom.rb', line 171

def at_xpath(selector, within: nil)
  expr = <<~JS
    function(selector, within) {
      within ||= document
      let xpath = document.evaluate(selector, within, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      return xpath.snapshotItem(0);
    }
  JS
  evaluate(expr, selector, within)
end

#css(selector, within: nil) ⇒ Array<Node>

Finds nodes by using a CSS path selector.

Examples:

browser.go_to("https://github.com/")
browser.css("a[aria-label='Issues you created']") # => [Node]

Parameters:

  • selector (String) —

    The CSS path selector.

  • within (Node, nil) (defaults to: nil) —

    The parent node to search within.

  • within: (Object, nil) (defaults to: nil)

Returns:

  • (Array<Node>) —

    The matching nodes.

Raises:



200
201
202
203
204
205
206
207
208
209
# File 'lib/ferrum/frame/dom.rb', line 200

def css(selector, within: nil)
  expr = <<~JS
    function(selector, within) {
      within ||= document
      return Array.from(within.querySelectorAll(selector));
    }
  JS

  evaluate(expr, selector, within)
end

#doctype ⇒ String?

Returns current document's doctype declaration.

Examples:

browser.go_to("https://example.com")
browser.doctype # => "<!DOCTYPE html>"

Returns:

  • (String, nil) —

    The serialized <!DOCTYPE ...> declaration, or nil if the document has none.

Raises:



78
79
80
# File 'lib/ferrum/frame/dom.rb', line 78

def doctype
  evaluate("document.doctype && new XMLSerializer().serializeToString(document.doctype)")
end

#frame_element ⇒ Node?

Returns the element in which the window is embedded.

Examples:

browser.go_to("https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe")
frame = browser.frames.last
frame.frame_element # => [Node]
frame.parent.parent.parent.frame_element # => nil

Returns:

  • (Node, nil) —

    The element in which the window is embedded, nil for the main frame and for a frame from a different origin than its parent.

Raises:



113
114
115
# File 'lib/ferrum/frame/dom.rb', line 113

def frame_element
  evaluate("window.frameElement")
end

#html ⇒ String

Returns the HTML of the whole document, <html> included.

Examples:

browser.go_to("https://google.com/")
browser.html # => '<html itemscope="" itemtype="http://schema.org/WebPage" lang="ru"><head>...

Returns:

  • (String) —

    The document's outerHTML, empty when it has no root element.

Raises:



94
95
96
# File 'lib/ferrum/frame/dom.rb', line 94

def html
  evaluate("document.documentElement?.outerHTML") || ""
end

#wait_css(selector, within: nil, timeout: nil, interval: WAIT_INTERVAL) ⇒ Node?

Polls #at_css until a node matches the selector.

Examples:

browser.wait_css("#appears_later") # => Node

Parameters:

  • selector (String) —

    The CSS selector.

  • within (Node, nil) (defaults to: nil) —

    The parent node to search within.

  • timeout (Numeric, Deadline, nil) (defaults to: nil) —

    How long to keep trying, the page's timeout by default.

  • interval (Numeric) (defaults to: WAIT_INTERVAL) —

    Seconds to sleep between the attempts.

  • within: (Node, nil) (defaults to: nil)
  • timeout: (::Numeric, Deadline, nil) (defaults to: nil)
  • interval: (::Numeric) (defaults to: WAIT_INTERVAL)

Returns:

  • (Node, nil) —

    The matching node, nil if none shows up in time.



261
262
263
# File 'lib/ferrum/frame/dom.rb', line 261

def wait_css(selector, within: nil, timeout: nil, interval: WAIT_INTERVAL)
  Utils::Poll.call(timeout || @page.timeout, interval) { at_css(selector, within: within) }
end

#wait_css!(selector, **options) ⇒ Node

Same as #wait_css, but raises if no node matches in time.

Parameters:

  • selector (String)
  • options (Hash) —

    The options of #wait_css.

  • within: (Node, nil)
  • timeout: (::Numeric, Deadline, nil)
  • interval: (::Numeric)

Returns:

Raises:



278
279
280
# File 'lib/ferrum/frame/dom.rb', line 278

def wait_css!(selector, **options)
  wait_css(selector, **options) || raise(TimeoutError)
end

#wait_xpath(selector, within: nil, timeout: nil, interval: WAIT_INTERVAL) ⇒ Node?

Polls #at_xpath until a node matches the selector.

Examples:

browser.wait_xpath("//div[@id='appears_later']") # => Node

Parameters:

  • selector (String) —

    The XPath selector.

  • within (Node, nil) (defaults to: nil) —

    The parent node to search within.

  • timeout (Numeric, Deadline, nil) (defaults to: nil) —

    How long to keep trying, the page's timeout by default.

  • interval (Numeric) (defaults to: WAIT_INTERVAL) —

    Seconds to sleep between the attempts.

  • within: (Node, nil) (defaults to: nil)
  • timeout: (::Numeric, Deadline, nil) (defaults to: nil)
  • interval: (::Numeric) (defaults to: WAIT_INTERVAL)

Returns:

  • (Node, nil) —

    The matching node, nil if none shows up in time.



303
304
305
# File 'lib/ferrum/frame/dom.rb', line 303

def wait_xpath(selector, within: nil, timeout: nil, interval: WAIT_INTERVAL)
  Utils::Poll.call(timeout || @page.timeout, interval) { at_xpath(selector, within: within) }
end

#wait_xpath!(selector, **options) ⇒ Node

Same as #wait_xpath, but raises if no node matches in time.

Parameters:

  • selector (String)
  • options (Hash) —

    The options of #wait_xpath.

  • within: (Node, nil)
  • timeout: (::Numeric, Deadline, nil)
  • interval: (::Numeric)

Returns:

Raises:



320
321
322
# File 'lib/ferrum/frame/dom.rb', line 320

def wait_xpath!(selector, **options)
  wait_xpath(selector, **options) || raise(TimeoutError)
end

#xpath(selector, within: nil) ⇒ Array<Node>

Finds nodes by using a XPath selector.

Examples:

browser.go_to("https://github.com/")
browser.xpath("//a[@aria-label='Issues you created']") # => [Node]

Parameters:

  • selector (String) —

    The XPath selector.

  • within (Node, nil) (defaults to: nil) —

    The parent node to search within.

  • within: (Object, nil) (defaults to: nil)

Returns:

  • (Array<Node>) —

    The matching nodes.

Raises:



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/ferrum/frame/dom.rb', line 135

def xpath(selector, within: nil)
  expr = <<~JS
    function(selector, within) {
      let results = [];
      within ||= document

      let xpath = document.evaluate(selector, within, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
      for (let i = 0; i < xpath.snapshotLength; i++) {
        results.push(xpath.snapshotItem(i));
      }

      return results;
    }
  JS

  evaluate(expr, selector, within)
end