使用 CefSharp 检测 URL 更改

我正在创建一个使用 CefSharp 73.1.130 的软件。我需要在 URL 更改时或至少在页面加载时进行一些检查。


我已经尝试了很多东西,例如:


browser.RenderProcessMessageHandler = new RenderProcessMessageHandler();


public class RenderProcessMessageHandler: IRenderProcessMessageHandler {

    // 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) {

        const string script = "document.addEventListener('DOMContentLoaded', function(){ alert('DomLoaded'); });";


        frame.ExecuteJavaScriptAsync(script);

    }

}


//Wait for the page to finish loading (all resources will have been loaded,     rendering is likely still happening)

browser.LoadingStateChanged += (sender, args) => {

    //Wait for the Page to finish loading

    if (args.IsLoading == false) {

        browser.ExecuteJavaScriptAsync("alert('All Resources Have Loaded');");

    }

}

和这个 :


    browser.LoadingStateChanged += OnLoadingStateChanged;

private void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs args) {

    if (!args.IsLoading) {

        // Page has finished loading, do whatever you want here

    }

}

但我不确定我是否正确使用它,所以我每次都会收到错误消息,例如“该名称在当前上下文中不存在”。


这是我的 CefSharp 代码:


    public CefSharp.WinForms.ChromiumWebBrowser browser;

private void InitializeChromium() {

    CefSettings settings = new CefSettings();

    Cef.Initialize(settings);

    browser = new CefSharp.WinForms.ChromiumWebBrowser("https://google.com/");

    browser.Dock = DockStyle.Fill;


    this.wb_panel.Controls.Add(browser);

}

我希望获得新的 url 作为输出以在 RichTextBox 中显示它


扬帆大鱼
浏览 455回答 1
1回答

临摹微笑

您可以ChromiumWebBrowser_AddressChanged在代码中使用事件。ChromiumWebBrowser.AddressChanged事件在图书馆网站上有描述。这是你应该如何使用它:订阅事件:browser.AddressChanged += OnBrowserAddressChanged;定义OnBrowserAddressChangedbody 到 changeRichBoxText值:this.InvokeOnUiThreadIfRequired(() => richTextBox1.Text = e.Address);完毕这是完整的例子:using CefSharp;using CefSharp.WinForms;using CefSharp.WinForms.Internals;using System;using System.Windows.Forms;namespace WindowsFormsApp2{    public partial class Form1 : Form    {        private readonly ChromiumWebBrowser browser;        public Form1()        {            InitializeComponent();            browser = new ChromiumWebBrowser("www.google.com")            {                Dock = DockStyle.Fill,            };            browser.AddressChanged += OnBrowserAddressChanged;            Controls.Add(browser);        }        private void OnBrowserAddressChanged(object sender, AddressChangedEventArgs e)        {            this.InvokeOnUiThreadIfRequired(() => Text = e.Address);        }    }}
打开App,查看更多内容
随时随地看视频慕课网APP