How can my Python script get the URL of the currently active Google Chrome tab in Windows? This has to be done without interrupting the user, so sending key strokes to copy/paste is not an option.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
First, you need to download and install pywin32. Import these modules in your script:
If Google Chrome is the currently active window, first get the window handle by:
(Otherwise, find the Google Chrome window handle by using
win32gui.FindWindow. Windows Detective is handy when finding out class names for windows.)It seems the only way to get the URL is to get the text in the “omnibox” (address bar). This is usually the tab’s URL, but could also be any partial URL or search string that the user is currently typing.
Also, the URL in the omnibox won’t include the “http://” prefix unless the user has typed it explicitly (and not yet pressed enter), but it will in fact include “https://” or “ftp://” if those protocols are used.
So, we find the omnibox child window inside the current Chrome window:
This will of course break if the Google Chrome team decides to rename their window classes.
And then we get the “window text” of the omnibox, which doesn’t seem to work with
win32gui.GetWindowTextfor me. Good thing there’s an alternative that does work:This little function sends the WM_GETTEXT message to the window and returns the window text (in this case, the text in the omnibox).
There you go!