프로그래밍/c#

C# cefSharp 이용시 개발자도구 보고 싶을때

소행성왕자 2020. 10. 6. 15:26

C# cefSharp 이용시 개발자도구 보고 싶을때

참고 https://github.com/cefsharp/CefSharp/wiki/General-Usage#initialize-and-shutdown

c# 에서 크로미움 브라우져 사용시 (version 84)

개발자 도구를 보고 싶을때가 있다.

var settings = new CefSettings();

settings.Locale = "ko";

settings.RemoteDebuggingPort = 8087;

위와같이 셋팅후

브라우져에서 localhost:8087 접속하면 개발자 도구 사용할수 있습니다.

 

 

 

전체소스

cefShap 과 웹페이지 javascript bind 소스 포함

​
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
​
namespace Windowsujin
{
   public partial class Form1 : Form
   {
       public Form1()
       {
           InitializeComponent();
           InitBrowser();
       }
​
       public ChromiumWebBrowser browser;
       private BindingOptions options;
​
       public object EvaluateJavaScriptResult { get; private set; }
​
       public void InitBrowser()
       {
           var settings = new CefSettings();
         
           settings.Locale = "ko";
           settings.CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache");
​
           Debug.WriteLine(settings.CachePath);
​
           settings.RemoteDebuggingPort = 8087;
​
           Cef.Initialize(settings);
           browser = new ChromiumWebBrowser("http://xxxx.xxx.ogin.html");
           
           JsHandler jh = new JsHandler();
           browser.JsDialogHandler = jh;
​
           this.panel1.Size = new Size(1200, 800);
           this.panel1.Controls.Add(browser);
           browser.Dock = DockStyle.Fill;


           //webpage_load_finish();
           //frame_load_finish();

​
           /**
            *
            * csharp -> js 호출
            *
            */
           //browser.RenderProcessMessageHandler = new RenderProcessMessageHandler();
​
​
           //js_csharp_bind();
​
       }
​
       private void Form1_Load(object sender, EventArgs e)
       {
​
       }
​
       /**
        *
        *  js -> csharp 클래스 호출
        *  
        *  [1006/105953.433:INFO:CONSOLE(1885)] "Uncaught (in promise) ReferenceError: assert is not defined", source: http://devpush.iptime.org/community/example_file_upload.html (1885)
        *
        */
       private void js_csharp_bind()
       {
           browser.JavascriptObjectRepository.Register("boundAsync", new BoundObject(), true, options);
           browser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender, e) =>
           {
               var name = e.ObjectName;
​
               Debug.WriteLine("aaasdf");
               Debug.WriteLine($"Object {e.ObjectName} was bound successfully.");
​
           };
       }
​
       /**
        *
        * 페이지로드가 완료 될 때까지 기다립니다 (모든 리소스가로드되고 렌더링이 계속 진행될 수 있음).
        *
        */
       private void webpage_load_finish()
       {
           //페이지로드가 완료 될 때까지 기다립니다 (모든 리소스가로드되고 렌더링이 계속 진행될 수 있음).
           browser.LoadingStateChanged += (sender, args) =>
           {
               //Wait for the Page to finish loading
               if (args.IsLoading == false)
               {
                   browser.ExecuteScriptAsync("alert('All Resources Have Loaded');");
                   browser.ExecuteScriptAsync("document.body.style.background = 'red';");
​
               }
           };
       }
​
       /**
        *
        * MainFrame 로드를 완료 할 때까지 기다립니다.
        *
        */
       private void frame_load_finish()
       {
           // MainFrame이로드를 완료 할 때까지 기다립니다.
           browser.FrameLoadEnd += (sender, args) =>
           {
               //Wait for the MainFrame to finish loading
               if (args.Frame.IsMain)
               {
                   args.Frame.ExecuteJavaScriptAsync("alert('MainFrame finished loading');");
                   browser.ExecuteScriptAsync("document.body.style.background = 'blue';");
                   browser.ExecuteScriptAsync("aa();");
​
                   Task task = new Task(() => {
                       //object js = EvaluateScript(browser, "document.getElementsByTagName('html')[0].innerHTML;");
                       object js = EvaluateScript(browser, "bb();");
                       Debug.WriteLine(js.ToString());
​
                       string json = js.ToString().Trim();
                       Debug.WriteLine(json);
                       JObject applyJObj = JObject.Parse(json.Trim());
                       string nick = applyJObj["field1"].ToString();
                       string id = applyJObj["field2"].ToString();
                       Debug.WriteLine($"nick -> {nick}");
                       Debug.WriteLine($"id -> {id}");
​
​
                   });
                   task.Start();
​
                   
               }
           };
       }
​
​
       static object EvaluateScript(ChromiumWebBrowser b, string script)
       {
           var task = b.EvaluateScriptAsync(script);
           task.Wait();
           JavascriptResponse response = task.Result;
           return response.Success ? (response.Result ?? "") : response.Message;
       }
​
​
   }
}
​
public class BoundObject
{
   public int Add(int a, int b)
   {
       return a + b;
   }
}
​
public class RenderProcessMessageHandler : IRenderProcessMessageHandler
{
   public object EvaluateJavaScriptResult { get; private set; }
​
   public void OnContextReleased(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame)
   {
       throw new NotImplementedException();
   }
​
   public void OnFocusedNodeChanged(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IDomNode node)
   {
       throw new NotImplementedException();
   }
​
   public void OnUncaughtException(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, JavascriptException exception)
   {
       throw new NotImplementedException();
   }
​
   // Wait for the underlying JavaScript Context to be created. This is only called for the main frame.
   // If the page has no JavaScript, no context will be created.
   void IRenderProcessMessageHandler.OnContextCreated(IWebBrowser browserControl, IBrowser browser, IFrame frame)
   {
       SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
​
       /**
        * js 메소드 삽입
        */
       //const string script = "document.addEventListener('DOMContentLoaded', function(){ alert('DomLoaded'); });";
       //frame.ExecuteJavaScriptAsync(script);
​
​
​
       /*
       // Get Document Height
       //var task = frame.EvaluateScriptAsync("(function() { var body = document.body, html = document.documentElement; return  Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); })();");
       var task = frame.EvaluateScriptAsync("(function() { document.getElementById('bbsList'); })();");
       
       //Continue execution on the UI Thread
       task.ContinueWith(t =>
       {
           if (!t.IsFaulted)
           {
               var response = t.Result;
​
               //EvaluateJavaScriptResult = response.Success ? (response.Result ?? "null") : response.Message;
               EvaluateJavaScriptResult = response.Message;
               MessageBox.Show(EvaluateJavaScriptResult.ToString());
           }
       }, TaskScheduler.FromCurrentSynchronizationContext());
       */
​
   }
}
​
​
public class JsHandler : IJsDialogHandler
{
   public bool OnBeforeUnloadDialog(IWebBrowser chromiumWebBrowser, IBrowser browser, string messageText, bool isReload, IJsDialogCallback callback)
   {
       //throw new NotImplementedException();
       return true;
   }
​
   public void OnDialogClosed(IWebBrowser chromiumWebBrowser, IBrowser browser)
   {
       //throw new NotImplementedException();
​
   }
​
   public bool OnJSDialog(IWebBrowser browserControl, IBrowser browser, string originUrl, CefJsDialogType dialogType, string messageText, string defaultPromptText, IJsDialogCallback callback, ref bool suppressMessage)
   {
​
​
       String type = dialogType.ToString().ToLower();
       if (type == "confirm")
       {
           DialogResult result = MessageBox.Show(messageText, "트레이딩 커뮤니티", MessageBoxButtons.OKCancel);
           switch (result)
           {
               case DialogResult.OK: { callback.Continue(true); break; }
               case DialogResult.Cancel: { callback.Continue(false); break; }
           }
       }
       else
       {
           DialogResult result = MessageBox.Show(messageText, "트레이딩 커뮤니티");
           callback.Continue(true);
       }
​
       return true;
   }
​
   public void OnResetDialogState(IWebBrowser chromiumWebBrowser, IBrowser browser)
   {
       //throw new NotImplementedException();
   }
}