C# Get the URL of the active tab of browser

Solution 1:

I have found solution which works for me for all browsers tested on (Yandex (chromium based) Chrome and Firefox it works on all three).

First I changed from using System.Windows.Automation to IUIAutomation because the former was really slow.

So for everyone looking for solution to similar problem first go to dependencies and right click to dependencies and press "Add COM Reference..": enter image description here

Then find UIAutomationClient you could put UI in the search bar top right to find it easily: enter image description here After you have added it here is the code:

private readonly CUIAutomation _automation;
        public YourMainClass()
        {
            _automation = new CUIAutomation();
            _automation.AddFocusChangedEventHandler(null, new FocusChangeHandler(this));
        }

        public class FocusChangeHandler : IUIAutomationFocusChangedEventHandler
        {
            private readonly YourMainClass _listener;

            public FocusChangeHandler(YourMainClass listener)
            {
                _listener = listener;
            }

            public void HandleFocusChangedEvent(IUIAutomationElement element)
            {
                if (element != null)
                {
                    using (Process process = Process.GetProcessById(element.CurrentProcessId))
                    {
                        try
                        {
                            IUIAutomationElement elm = this._listener._automation.ElementFromHandle(process.MainWindowHandle);
                            IUIAutomationCondition Cond = this._listener._automation.CreatePropertyCondition(30003, 50004);
                            IUIAutomationElementArray elm2 = elm.FindAll(TreeScope.TreeScope_Descendants, Cond);
                            for (int i = 0; i < elm2.Length; i++)
                            {
                                IUIAutomationElement elm3 = elm2.GetElement(i);
                                IUIAutomationValuePattern val = (IUIAutomationValuePattern)elm3.GetCurrentPattern(10002);
                                if (val.CurrentValue != "")
                                {
                                    Debug.WriteLine("URL found: " + val.CurrentValue);
                                }
                            }
                        }
                        catch { }

                    }
                }
            }
        }

And at the very top put these two lines

using UIAutomationClient;
using TreeScope = UIAutomationClient.TreeScope;

And also you should change "YourMainClass" with your own class as needed.