WebEngineでJRubyとHTML間で連携をしてみる

JRuby(JRubyFX)とWebView上のHTMLの連携を試してみる。

JRuby側のボタンを押したらHTML上のspanにメッセージを表示して、
HTML上のボタンを押したらJRuby側のラベルにメッセージを表示する

プログラムは、RubyコードとHTMLコードの2つを用意します。

require 'jrubyfx'

class App < JRubyFX::Application

  def start(stage)
    with(stage, width: 800, height: 600, title: "sample") do
      layout_scene do
        vbox do
          hbox do
            button(id:"fx-btn", text:"click", min_width: 100)
            label(id:"fx-msg", text:"=== ===")
          end
          web_view(id:"browser") do |v| 
            v.engine.load "file:///path/to/sample.html"
            v.engine.set_java_script_enabled true
          end
        end
      end 
      show
    end 

    stage['#fx-btn'].set_on_action do
      doc = stage['#browser'].engine.get_document
      doc.get_element_by_id("web-msg").set_text_content "clicked javafx button."
    end 

    stage['#browser'].engine.get_load_worker.state_property.add_change_listener do |ov,os,new_state|
      if new_state == Worker::State::SUCCEEDED
        el = Proc.new do
          stage['#fx-msg'].text = " clicked browser button !!!"
        end
        doc = stage['#browser'].engine.get_document
        doc.get_element_by_id('web-btn').add_event_listener( "click", el, false)
      end 
    end 

  end 
end

App.launch
  • sample.html
<html>
<head>
  <title>sample</title>
</head>
<body>
  <p>hello sample.</p>
  <input type="button" id="web-btn" value="button" /><br/>
  message: <span id="web-msg">hogehoge</span><br/>
</body>
</html>

実行すると、こんな感じになります。


普通にGUIでいいじゃんって話なんですが、どうしてもJavascriptGUIRubyから扱いたくて、現在試行錯誤中です。
これであとはRubyからJavascriptにアクセスできればやりたいことができそうな気がします。