0

I was trying to use uiautomation's python wrapper to get the active url of a chrome window. However, this script was only getting certain websites (such as youtube or google) and not others (stackoverflow, reddit, github etc.)

import win32gui as win
import time
import uiautomation as auto

while True:
    window = win.GetForegroundWindow()
    win_name = win.GetWindowText(window)
    if "Google Chrome" in win_name:
        chromeControl = auto.ControlFromHandle(window)
        edit = chromeControl.EditControl()
        print('https://' + edit.GetValuePattern().Value)

I have tried almost every post regarding this matter to no avail. Apparently chrome has changed their window class names etc. Any help would be appreciated.

Shaurya
  • 25
  • 5
  • What is your program as whole meant to do? There might be another library which is better suited to the task. – AMC Jan 05 '20 at 02:36
  • I want to get the active application, but if the application is chrome: get the url or base website. – Shaurya Jan 05 '20 at 06:28
  • Ah, never mind then. – AMC Jan 05 '20 at 06:29
  • Does this answer your question? [Get Chrome tab URL in Python](https://stackoverflow.com/questions/52675506/get-chrome-tab-url-in-python) – skjerns Jan 26 '20 at 14:02

1 Answers1

0

Here's a simple way to do it:

import uiautomation as auto


control = auto.GetFocusedControl()
controlList = []
while control:
    controlList.insert(0, control)
    control = control.GetParentControl()
    
control = controlList[0 if len(controlList) == 1 else 1]
    
address_control = auto.FindControl(control, lambda c, d: 
                                            isinstance(c, auto.EditControl))

print('Current URL:')
print(address_control.GetValuePattern().Value)

you can also then set some new value for the OmniBox:

address_control.GetValuePattern().SetValue('http://some_url')
macsunmood
  • 1
  • 1
  • 1
  • 1