naqvis / webview

Crystal bindings to Webview library
MIT License
93 stars 8 forks source link

Question : example of use of : webview::Webview#eval #6

Closed serge-hulne closed 2 years ago

serge-hulne commented 2 years ago

Hi, Could you please provide an example of use of : webview::Webview#eval

More precisely : in the context of manipulating the DOM (adding a DIV to the current root document, for instance).

Thanks

naqvis commented 2 years ago

Hi @serge-hulne

Webview#eval is used to inject JavaScript to loaded document.

for development/debugging purposes, you can toggle the debug flag to true of Webview#window method, this will enable opening debug console (via mouse right click) of browser used.

html = <<-HTML
<!DOCTYPE html><html lang="en-US">
<head>
<title>Hello,World!</title>
</head>
<body>
  <button onClick="add(document.body.children.length)">Add</button>
</body>
</html>
HTML

inject = <<-JS
  elem = document.createElement('div');  
  elem.innerHTML = "hello webview %s";
  document.body.appendChild(elem);
JS

wv = Webview.window(640, 480, Webview::SizeHints::NONE, "Hello WebView", "data:text/html,#{html}" , true)

wv.bind("add", Webview::JSProc.new { |n|
  wv.eval(sprintf(inject, n))
  JSON::Any.new(nil)
})

wv.run
wv.destroy

image

serge-hulne commented 2 years ago

Thank you very much @naqvis !