webview2 C#で専用ブラウザーを作ってみよう! 二回目

Windows用のWebView2は強力にJavaScliptを制御できます。この機能を利用してヤフーの雨雲レーダーを改造して自分だけの雨雲レーダーアプリを作成していきましょう!

前回はプロジェクトを作成してWebview2のランタイムを導入したところで終わりました。
webview2 C#で専用ブラウザーを作ってみよう! 一回目

 

 

Webview2の初期化設定をプログラミングします。
Form1.csに次のプログラムを丸ごとコピーする。アプリネームを「test」以外のせってにするとエラーの原因です。namespaceを自分のプロジェクトに合わせましょう。

using Microsoft.Web.WebView2.Core;
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitializewebView();
        }
        private async void InitializewebView()
        {
            //Webview2のランタイムパス設定
            string path_runtime = Application.StartupPath + @"\Microsoft.WebView2.FixedVersionRuntime";
            //Webview2の設定ファイル保存先を設定
            var userfolder = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\testuser";
            //上記フォルダーの作成
            System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo(userfolder);
            directory.Create();
            //Webview2の初期化設定 ランタイムのPathと設定初期データのPathを登録する。パッケージタイプでの利用可能にする。
            var webenvi = await CoreWebView2Environment.CreateAsync(path_runtime, userfolder);
            await webView21.EnsureCoreWebView2Async(webenvi);
            //UserAgentの設定 Firefoxとしている
            webView21.CoreWebView2.Settings.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0";
            //webView2の初期設定が完了するまで待機
            await Task.Run(() =>
            {
                this.Invoke(new Action(() =>
                {
                    while (webView21.CoreWebView2 == null)
                    {
                        Task.Delay(500);
                    }
                }));
            });
            //webView2の読み込み開始と読み込み完了のイベントを設定
            webView21.NavigationCompleted += WebView_NavigationCompleted;
            webView21.NavigationStarting += WebView_NavigationStarting;

            //ヤフーの雨雲レーダーを読み込み
            webView21.CoreWebView2.Navigate("https://weather.yahoo.co.jp/weather/zoomradar/");
        }
        private  void WebView_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
        {
        }
        private  void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
        }
    }
}

起動すると次のように雨雲レーダーが表示される。
ここから不要な情報を削っていくが前回のJavascliptをそのまま利用する。

このスクリプトが重要になります。javascliptなのでC#ではそのままでは動きません。

document.getElementById('header').innerHTML='';
document.getElementById('smapModule1').innerHTML="";
document.getElementById('mapTab').innerHTML="";
document.getElementById('ydn-bot').style='display:none';
document.getElementsByClassName('mapFailureInfo')[0].outerHTML="<div class='mapFailureInfo'></div><style>#wrapper:not(.full) #yjMapMain{left:0px!important}</style>";

 

Javascliptを動作させるためには次のコマンドを使用します。

await webView.CoreWebView2.ExecuteScriptAsync("");

上記スクリプトではC#上でうまく動かないため少し次のように書き換えます。
WebView_NavigationCompletedを次に置き換えます。

private async void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
    await webView21.CoreWebView2.ExecuteScriptAsync(
            @"document.getElementById('header').innerHTML='';" +
            @"document.getElementById('smapModule1').innerHTML='';" +
            @"document.getElementById('mapTab').innerHTML='';" +
            @"document.getElementById('ydn-bot').style='display:none';" +
            @"document.getElementsByClassName('mapFailureInfo')[0].outerHTML='<divclass=mapFailureInfo></div>"+
            @"<style>#wrapper:not(.full) #yjMapMain{left:0px!important}</style>';"
            );
}

ん~ なんか思っていたような表示にはならなかったけどま~手始めにやる内容としては上出来ですね!

本当は画面いっぱいに表示したかったのですが、タイムアップです。皆さんで頑張ってみてください!
マップの表示領域を変更しているのはjavascliptっぽいので難しいかもですね!
もしやるとするとパネルにWebview2を入れてマップの表示領域に限定する方法がありますね!

頑張るとこんな感じにできます。