Eto.FormsでWebブラウザ
Eto.FormsはWebViewクラスでWebブラウザの利用が可能です。
では、さっそく簡単なサンプルを。 こんな感じです。
では、例によっていつものセッティングです。
using System; using Eto.Forms; using Eto.Drawing; namespace EtoSample08 { public class MainForm : Form { private TextBox urlText = new TextBox { PlaceholderText = "URL here..." }; private WebView browser = new WebView { }; public MainForm() { Title = "Eto Browser"; ClientSize = new Size(600, 300); urlText.KeyUp += (s, e) => { if (e.KeyData == Keys.Enter) { browser.Url = new Uri(urlText.Text); } }; Content = new StackLayout { Padding = 10, HorizontalContentAlignment = HorizontalAlignment.Stretch, Items = { urlText, new StackLayoutItem(browser,true), }, }; var actionCommand = new Command { MenuText = "Change", ToolBarText = "Change", Enabled = false }; var script = "document.getElementById('test').innerHTML='[CLICKED]';"; actionCommand.Executed += (s, e) => browser.ExecuteScript(script); var quitCommand = new Command { MenuText = "Quit" }; quitCommand.Executed += (sender, e) => Application.Instance.Quit(); Menu = new MenuBar { Items = { new ButtonMenuItem { Text = "&File", Items = { actionCommand } }, }, ApplicationItems = { new ButtonMenuItem { Text = "&Preferences..." }, }, QuitItem = quitCommand, }; ToolBar = new ToolBar { Items = { actionCommand } }; browser.DocumentLoaded += (s, e) => actionCommand.Enabled = true; var html = "<!DOCTYPE html><title>Hello!</title>" + "<p>User Agent:<script>document.write(window.navigator.userAgent)</script></p>" + "<p>日本語テスト</p>" + "<p id='test'>test2</p>"; browser.LoadHtml(html); } } }
起動します。
ツールバー(またはメニューバー)の「Change」をクリックすると、ブラウザ末尾が書き換わります。
次に上部テキストボックスに「https://google.com」と入力してみました。
コードを見れば分かると思いますが、上のボックスに「正しいURI」を入れてenterキーを押すとジャンプします。
例外処理など一切ないので、単に「google.com」とか入れると例外で落ちます。
WebViewクラス
Url
プロパティにUriインスタンスを設定するとジャンプLoadHtml
メソッドで、HTMLを直接設定- .NET側からブラウザ側へのアクセスは、
ExecuteScript
メソッド - ブラウザ(JavaScript)側から.NET側へのアクセスは、現状では不可能
WebViewクラスで使うブラウザは?
ところで、起動時画面にユーザエージェントを表示させたのですが、これはIE7です。 これは、Windowsで使うブラウザコンポーネントの既定値です。
実際にインストールされているのがIE11でも、コンポーネントはIE7になってしまいます。 もちろん描画仕様もIE7なので、かなり悲惨です。
対策はレジストリの設定です。
Eto.Formsの場合、Windows専用コードが必要になっちゃいますね。
IE7のような、とっくにサポートも終わり、古い仕様のエンジンで嬉しいケースは(一部社内イントラWebアプリなどを除いて)ほとんどないので、Eto側で対応してほしいところです。
レジストリを汚してしまうので、コンストラクタのオプションにすべきかもしれませんが。
Linuxで実行
いつもの必須ファイルをLinux Mint18にコピーして、起動してみました。
ぱっと見では、搭載するChromiumをGTK#から扱っているようですね。実際、メーリングリストでのやり取りにある通り、webkit-sharpを使っているようです。
もちろんスクリプトも動作しますし、普通のブラウザとしてのアクセスも可能です。