How do I get the URL of the active Google Chrome tab in Windows?

How will my Python script get the URL of the active Google Chrome active tab in Windows? This must be done without interrupting the user, so sending strokes to copy / paste is not an option.

+8
python google-chrome winapi
source share
2 answers

First you need to download and install pywin32 . Import these modules into the script:

import win32gui import win32con 

If Google Chrome is the current active window, first get the window handle:

 hwnd = win32gui.GetForegroundWindow() 

(Otherwise, locate the Google Chrome window handle using win32gui.FindWindow . Windows Detective is useful when looking for class names for windows.)

It seems the only way to get the url is to get the text in "omnibox" (address bar) . This is usually the tab URL, but it can also be part of the partial URL or search bar that the user is currently typing.

In addition, the omnibox URL will not include the "http: //" prefix unless the user has typed it explicitly (and has not yet hit enter), but will actually include "https: //" or "ftp: / / "if these protocols are used.

So, we find the omnibox child window inside the current Chrome window:

 omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None) 

This, of course, will break if the Google Chrome team decides to rename their window classes.

And then we get omnibox “text text” that doesn't seem to work with win32gui.GetWindowText for me. It’s good that there is an alternative that works:

 def getWindowText(hwnd): buf_size = 1 + win32gui.SendMessage(hwnd, win32con.WM_GETTEXTLENGTH, 0, 0) buf = win32gui.PyMakeBuffer(buf_size) win32gui.SendMessage(hwnd, win32con.WM_GETTEXT, buf_size, buf) return str(buf) 

This small function sends a WM_GETTEXT message to the window and returns the text of the window (in this case, the text in the omnibox).

There you go!

+13
source share

The Christian answer did not work for me, since the internal structure of Chrome has completely changed, and you can no longer access the elements of the Chrome window using win32gui.

The only possible way I managed to find is to use the UI API, which this python wrapper with some use cases

Run this and switch to the Chrome window from which you want to get the address:

 from time import sleep import uiautomation as automation if __name__ == '__main__': sleep(3) control = automation.GetFocusedControl() controlList = [] while control: controlList.insert(0, control) control = control.GetParentControl() if len(controlList) == 1: control = controlList[0] else: control = controlList[1] address_control = automation.FindControl(control, lambda c, d: isinstance(c, automation.EditControl) and "Address and search bar" in c.Name) print address_control.CurrentValue() 
+2
source share

All Articles