User Tools

Site Tools


study:cs-webbrowser:20250321-001:index

C# CefSharp 如何等待頁面載入載入後,填入帳號與密碼,並觸發按下Login Event (2025-03-21)

  • 在 C# 中使用 CefSharp 等待頁面載入完成並自動填入帳號與密碼後觸發登入事件,可以透過以下步驟來實現:

AI Answer

  • 1. 等待頁面載入完成
    • 使用 LoadingStateChanged 事件來監聽頁面載入狀態。
    • browser.LoadingStateChanged += (sender, args) =>
      {
          if (!args.IsLoading)
          {
              // 頁面載入完成
              FillCredentials();
          }
      };
  • 2. 填入帳號與密碼
    • 在頁面載入完成後,使用 JavaScript 填入帳號與密碼,並觸發登入事件。
    • private void FillCredentials()
      {
          string username = "your_username"; // 替換為實際的帳號
          string password = "your_password"; // 替換為實際的密碼
      
          string script = $@"
              document.getElementById('txtUserID').value = '{username}';
              document.getElementById('txtUserPW').value = '{password}';
              document.getElementById('ImageButton1').click(); // 觸發登入事件
          ";
      
          browser.ExecuteScriptAsync(script);
      }
  • 3. 完整範例
    • 以下是一個完整的範例,展示如何在 CefSharp 中實現上述功能:
    • using CefSharp;
      using CefSharp.WinForms;
      
      public class YourForm : Form
      {
          private ChromiumWebBrowser browser;
      
          public YourForm()
          {
              InitializeComponent();
              InitializeCef();
          }
      
          private void InitializeCef()
          {
              Cef.Initialize(new CefSettings());
              browser = new ChromiumWebBrowser("http://your-login-page-url");
              browser.LoadingStateChanged += OnLoadingStateChanged;
              this.Controls.Add(browser);
          }
      
          private void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
          {
              if (!e.IsLoading)
              {
                  // 頁面載入完成
                  FillCredentials();
              }
          }
      
          private void FillCredentials()
          {
              string username = "your_username"; // 替換為實際的帳號
              string password = "your_password"; // 替換為實際的密碼
      
              string script = $@"
                  document.getElementById('txtUserID').value = '{username}';
                  document.getElementById('txtUserPW').value = '{password}';
                  document.getElementById('ImageButton1').click(); // 觸發登入事件
              ";
      
              browser.ExecuteScriptAsync(script);
          }
      }

注意事項

  • 確保帳號和密碼的安全性,避免在代碼中硬編碼敏感信息。
  • 確保正確的元素 ID 與 HTML 結構,以便 JavaScript 能正確執行。

Note for loaded HTML

  • <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-TW" lang="zh-TW">
    <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta http-equiv="Content-Style-Type" content="text/css" /><title>
    	login
    </title>
    <style type="text/css">
    
    img {border: 0px}
    	
    body 
    {
    	text-align: center;
    }
    #wrapper 
    {
    	width: 980px;
    	margin: 0 auto;
    	text-align: left;
    }
    #header 
    {
    	position: absolute;
    	top: 100px;
    	width: 980px;
    	height: 362px;
    	background: #C7D5ED url(./App_image/login.png);
    }
    #account 
    {
    	position: absolute;
    	top: 150px;
    	left: 465px;
    }
    #passwd 
    {
    	position: absolute;
    	top: 216px;
    	left: 465px;
    }
    
    .enter
    {
    	position: absolute;
    	top: 260px;
    	left: 600px;
    	height: 21px;
    }
    
    .forget_passwd 
    {
    	position: absolute;
    	top: 255px;
    	left: 460px;
    	width: 85px;
    	height: 25px;
    }
    
    .contact_us
    {
    	position: absolute;
    	top: 266px;
    	left: 570px;
    	width: 85px;
    	height: 25px;
    }
     .cssVCE 
        {
    
            color :Black;        
        }
        
         .background
        {
    
         BACKGROUND: url(./App_image/to_pageback.gif) fixed;        
        }
    
    
    
        .auto-style1 {
            left: 492px;
            top: 170px;
        }
    
    
    
        .auto-style2 {
            position: absolute;
            top: 260px;
            left: 600px;
            height: 36px;
            width: 103px;
        }
    
    
    
    </style>
    </head>
    
    <body onload="document.getElementById('txtUserID').focus()" class="background">
    <form name="form1" method="post" action="./login.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">
    <div>
    <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
    <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTExNjgyNjI0MjFkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYDBQxJbWFnZUJ1dHRvbjEFDEltYWdlQnV0dG9uMgUMSW1hZ2VCdXR0b24zd2Xwpk/gjeSuLoWjmJzqaWd6d/Y13huFsVr/jsIy4Z0=" />
    </div>
    
    <script type="text/javascript">
    //<![CDATA[
    var theForm = document.forms['form1'];
    if (!theForm) {
        theForm = document.form1;
    }
    function __doPostBack(eventTarget, eventArgument) {
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
            theForm.__EVENTTARGET.value = eventTarget;
            theForm.__EVENTARGUMENT.value = eventArgument;
            theForm.submit();
        }
    }
    //]]>
    </script>
    
    
    <script src="/WebResource.axd?d=pK4AYT4RxQL0nCKsW6stat1eySeNpSCAqcp3d8aNJNQqwmBKtQEwILIP-_dL6LIEJAbgA4GQGTtjWSo-oDEZe6MWDKY69L3quPgH88RgHTo1&amp;t=637916664095938335" type="text/javascript"></script>
    
    
    <script src="/ScriptResource.axd?d=gpeM90Ei9HFKeJ73yyrpkN5ak5dGJXk_uHqMi2dOBD32RwA_rLvQKpzIGNukC1UTV5rJD6O1sEkTt0xmk5ItWH6xckCbifkapGHiALjtD0-L3oMSQqO8W9ZnrTPl5D9mvOQu9W6xVEL2IaK8Y6EOxotMBEcle6uD0hjYRWgKHp81&amp;t=554344f3" type="text/javascript"></script>
    <script src="/ScriptResource.axd?d=aW3qn-1Qo_Nle-Q6KO4Z7eQ4Ey6mtRyhu8BAF8PRACn2OPtj8W6pf_kLyR7rNNCaI-SL_O-ziXKEyQ7myLuirly96nYqWR94HF35epjDWfb6pOGeM86e3ePTZ_nxt99zKtP0m72xIFhw1z7F4uPEJCsQh5ahJuJSRToBnjkInguucgKAAeKAVVm5IyIvEnkj0&amp;t=ffffffffcc461371" type="text/javascript"></script>
    <script src="/ScriptResource.axd?d=G8W065HSOskqnO_KrtBqhq3-WzfrAqlqqicMsvUu-NdLHxM9m_KivFj8VDNy_Uw8V5mokP4HP1H6oSPGAbMczeScrcyE7_J-vTYxNppzRFxmsy96UK7ShDJADv4SOhOJ_9qTrSVeIg03mXcryyJhfH2J7_N5Qr9X_vw2_VFu35Z6BHvlqG56UkUnOj9NhF9k0&amp;t=ffffffffcc461371" type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[
    function WebForm_OnSubmit() {
    if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;
    return true;
    }
    //]]>
    </script>
    
    <div>
    
    	<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="C2EE9ABB" />
    </div>
    <div id="wrapper" >
    	<div id="header" >
    		<div id="account" class="auto-style1">
                <input name="txtUserID" type="text" id="txtUserID" style="width:150px;" />
            </div>
    		<div id="passwd">
                <input name="txtUserPW" type="password" id="txtUserPW" TextM="" ode="Password" style="width:150px;" />
            </div>
    
    		<input type="image" name="ImageButton1" id="ImageButton1" class="auto-style2" src="App_image/enter_y.png" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ImageButton1&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" style="border-width:0px;" />
            <!--
            <input type="image" name="ImageButton2" id="ImageButton2" class="forget_passwd" onMouseOver="this.src=&#39;./App_image/forget_passwd_y.gif&#39;" onMouseOut="this.src=&#39;./App_image/forget_passwd_w.gif&#39;" src="App_image/forget_passwd_w.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ImageButton2&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" style="border-width:0px;" />
    	    
            <input type="image" name="ImageButton3" id="ImageButton3" class="contact_us" onMouseOver="this.src=&#39;./App_image/contact_y.gif&#39;" onMouseOut="this.src=&#39;./App_image/contact_w.gif&#39;" src="App_image/contact_w.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ImageButton3&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" style="border-width:0px;" />
    	       -->
    		    		
    	</div>
        <span id="RequiredFieldValidator1" style="color:Red;visibility:hidden;">請輸入帳號</span>
        <br />        
        <span id="RegularExpressionValidator1" style="color:Red;visibility:hidden;">帳號必須是英文及數字</span>
    	<br />
        <span id="RequiredFieldValidator2" style="color:Red;visibility:hidden;">請輸入密碼</span>
    </div>
    <script type="text/javascript">
    //<![CDATA[
    Sys.WebForms.PageRequestManager._initialize('ScriptManager1', 'form1', [], [], [], 90, '');
    //]]>
    </script>
    
    
    <script type="text/javascript">
    //<![CDATA[
    var Page_Validators =  new Array(document.getElementById("RequiredFieldValidator1"), document.getElementById("RegularExpressionValidator1"), document.getElementById("RequiredFieldValidator2"));
    //]]>
    </script>
    
    <script type="text/javascript">
    //<![CDATA[
    var RequiredFieldValidator1 = document.all ? document.all["RequiredFieldValidator1"] : document.getElementById("RequiredFieldValidator1");
    RequiredFieldValidator1.controltovalidate = "txtUserID";
    RequiredFieldValidator1.errormessage = "請輸入帳號";
    RequiredFieldValidator1.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
    RequiredFieldValidator1.initialvalue = "";
    var RegularExpressionValidator1 = document.all ? document.all["RegularExpressionValidator1"] : document.getElementById("RegularExpressionValidator1");
    RegularExpressionValidator1.controltovalidate = "txtUserID";
    RegularExpressionValidator1.errormessage = "帳號必須是英文及數字";
    RegularExpressionValidator1.evaluationfunction = "RegularExpressionValidatorEvaluateIsValid";
    RegularExpressionValidator1.validationexpression = "\\w*";
    var RequiredFieldValidator2 = document.all ? document.all["RequiredFieldValidator2"] : document.getElementById("RequiredFieldValidator2");
    RequiredFieldValidator2.controltovalidate = "txtUserPW";
    RequiredFieldValidator2.errormessage = "請輸入密碼";
    RequiredFieldValidator2.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
    RequiredFieldValidator2.initialvalue = "";
    //]]>
    </script>
    
    
    <script type="text/javascript">
    //<![CDATA[
    
    var Page_ValidationActive = false;
    if (typeof(ValidatorOnLoad) == "function") {
        ValidatorOnLoad();
    }
    
    function ValidatorOnSubmit() {
        if (Page_ValidationActive) {
            return ValidatorCommonOnSubmit();
        }
        else {
            return true;
        }
    }
            
    document.getElementById('RequiredFieldValidator1').dispose = function() {
        Array.remove(Page_Validators, document.getElementById('RequiredFieldValidator1'));
    }
    
    document.getElementById('RegularExpressionValidator1').dispose = function() {
        Array.remove(Page_Validators, document.getElementById('RegularExpressionValidator1'));
    }
    
    document.getElementById('RequiredFieldValidator2').dispose = function() {
        Array.remove(Page_Validators, document.getElementById('RequiredFieldValidator2'));
    }
    //]]>
    </script>
    </form>
    </body>
    </html>

study/cs-webbrowser/20250321-001/index.txt · Last modified: 2025/03/21 08:22 (external edit)