Class: WebviewUtil::Window

Inherits:
Object
  • Object
show all
Defined in:
lib/webview_util.rb

Overview

A minimal wrapper around the webview C library.

Opens a native OS window (WebKit on macOS/Linux, WebView2 on Windows) and navigates it to a URL. Blocks in run until the window is closed.

Examples:

wv = WebviewUtil::Window.new(title: "My App", width: 1024, height: 768)
wv.navigate("http://localhost:9292")
wv.run

Instance Method Summary collapse

Constructor Details

#initialize(title: "App", width: 1024, height: 768, debug: false) ⇒ Window

Returns a new instance of Window.

Parameters:

  • title (String) (defaults to: "App")

    window title

  • width (Integer) (defaults to: 1024)

    initial width in pixels

  • height (Integer) (defaults to: 768)

    initial height in pixels

  • debug (Boolean) (defaults to: false)

    enable webview devtools / debug mode



36
37
38
39
40
# File 'lib/webview_util.rb', line 36

def initialize(title: "App", width: 1024, height: 768, debug: false)
  @window = WebviewUtil.webview_create(debug ? 1 : 0, nil)
  WebviewUtil.webview_set_title(@window, title)
  WebviewUtil.webview_set_size(@window, width, height, 0)
end

Instance Method Details

#bind(name, &block) ⇒ Object

Bind a Ruby block to a JavaScript function name. The block receives parsed JSON arguments.



77
78
79
80
81
82
83
84
85
86
87
# File 'lib/webview_util.rb', line 77

def bind(name, &block)
  callback = FFI::Function.new(:void, [:string, :string, :pointer]) do |_seq, req, _arg|
    block.call(*JSON.parse(req))
  rescue StandardError => e
    warn "WebviewUtil bind error: #{e.message}"
    terminate
  end
  @bindings ||= []
  @bindings << callback
  WebviewUtil.webview_bind(@window, name, callback, nil)
end

#eval(js) ⇒ Object

Evaluate JavaScript in the window context.

Parameters:

  • js (String)


65
66
67
# File 'lib/webview_util.rb', line 65

def eval(js)
  WebviewUtil.webview_eval(@window, js)
end

#init(js) ⇒ Object

Inject JavaScript that runs before any page script.

Parameters:

  • js (String)


71
72
73
# File 'lib/webview_util.rb', line 71

def init(js)
  WebviewUtil.webview_init(@window, js)
end

Navigate the window to url.

Parameters:

  • url (String)


44
45
46
# File 'lib/webview_util.rb', line 44

def navigate(url)
  WebviewUtil.webview_navigate(@window, url)
end

#runObject

Block until the window is closed by the user.

On Linux/GTK a GLib SIGINT handler is installed at the C level so that Ctrl+C exits the GTK main loop cleanly.



52
53
54
55
56
# File 'lib/webview_util.rb', line 52

def run
  WebviewUtil.webview_run(@window)
ensure
  WebviewUtil.webview_destroy(@window)
end

#terminateObject

Programmatically close the window.



59
60
61
# File 'lib/webview_util.rb', line 59

def terminate
  WebviewUtil.webview_terminate(@window)
end