How do I get the URL of the active Google Chrome tab in Windows?
First, you need to download and install pywin32. Import these modules in your script:
import win32gui
import win32con
If Google Chrome is the currently active window, first get the window handle by:
hwnd = win32gui.GetForegroundWindow()
(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:
omniboxHwnd = win32gui.FindWindowEx(hwnd, 0, 'Chrome_OmniboxView', None)
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.GetWindowText
for me. Good thing there's an alternative that does work:
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 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!
How can I get the URL of the current tab from a Google Chrome extension?
Use chrome.tabs.query()
like this:
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
let url = tabs[0].url;
// use `url` here inside the callback because it's asynchronous!
});
This requires that you request access to the chrome.tabs
API in your extension manifest:
"permissions": [ ...
"tabs"
]
It's important to note that the definition of your "current tab" may differ depending on your extension's needs.
Setting lastFocusedWindow: true
in the query is appropriate when you want to access the current tab in the user's focused window (typically the topmost window).
Setting currentWindow: true
allows you to get the current tab in the window where your extension's code is currently executing. For example, this might be useful if your extension creates a new window / popup (changing focus), but still wants to access tab information from the window where the extension was run.
I chose to use lastFocusedWindow: true
in this example, because Google calls out cases in which currentWindow
may not always be present.
You are free to further refine your tab query using any of the properties defined here: chrome.tabs.query
chrome extension code to get current active tab url and detect any url update in it as well
Below is a script which takes care of both the cases:
chrome.tabs.onActivated.addListener( function(activeInfo){
chrome.tabs.get(activeInfo.tabId, function(tab){
y = tab.url;
console.log("you are here: "+y);
});
});
chrome.tabs.onUpdated.addListener((tabId, change, tab) => {
if (tab.active && change.url) {
console.log("you are here: "+change.url);
}
});
How to get URL of active tab in browser in VB.net
Finally Found the answer to my Question,
I have blocked the requests receiving from other applications and focused only on the chrome browser
Dim hWnd As IntPtr = GetForegroundWindow()
Dim ProcessID As UInt32 = Nothing
GetWindowThreadProcessId(hWnd, ProcessID)
Dim Proc As Process = Process.GetProcessById(ProcessID)
str_application_category = Proc.MainModule.FileVersionInfo.ProductName
If str_application_category = "Google Chrome" Then
str_application_path = GetChromeActiveWindowUrl()
End If
Catch ex As Exception
End Try
C# Get the URL of the active tab of browser
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..":
Then find UIAutomationClient you could put UI in the search bar top right to find it easily:
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.
Python: Get active tab url from google chrome
The following code works as long as you click on the Chrome window before the end of the time.sleep(3) :
from win32gui import GetForegroundWindow
from win32process import GetWindowThreadProcessId
from pywinauto.application import Application
import time
time.sleep(3)
window = GetForegroundWindow()
tid, pid = GetWindowThreadProcessId(window)
app = Application(backend="uia").connect(process=pid, time_out=10)
dlg = app.top_window()
title = "Address and search bar"
url = dlg.child_window(title=title, control_type="Edit").get_value()
print(url)
How to get the current active tab from a new pop up window created by chrome.windows
Get the active tab before creating the window and pass the id as a URL parameter.
extension script:
async function openPopup() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
await chrome.windows.create({
url: `popup.html?${new URLSearchParams({
tabId: tab.id,
})}` ,
type: 'popup',
});
}
popup.html:
<script src="popup.js"></script>
popup.js:
const activeTabId = Number(new URLSearchParams(location.search).get('tabId'));
chrome.scripting.executeScript({ target: { tabId: activeTabId }, function: foo });
function foo() {
console.log('injected foo');
}
How to get the currently opened tab's URL in my page action popup?
Use chrome.tabs.query
with the following parameters:
- queryInfo object:
active: true
- To get the active tablastFocusedWindow: true
- To select the active window
- callback function:
This function receives one argument: An array of matched tabs. Since only one window can be active, and one tab within this window, the array has only one element. This element is an object with theTab
signature.
Code snippet:
// Do NOT forget that the method is ASYNCHRONOUS
chrome.tabs.query({
active: true, // Select active tabs
lastFocusedWindow: true // In the current window
}, function(array_of_Tabs) {
// Since there can only be one active tab in one active window,
// the array has only one element
var tab = array_of_Tabs[0];
// Example:
var url = tab.url;
// ... do something with url variable
});
The activeTab
permission is sufficient for this to work.
Related Topics
Python/Regex - How to Extract Date from Filename Using Regular Expression
Python Pandas: Nameerror: Name Is Not Defined
Paramiko Capturing Command Output
Python: Printing Horizontally Rather Than Current Default Printing
Valueerror: Feature_Names Mismatch: in Xgboost in the Predict() Function
Python List - Only Keep Only-Positive or Only-Negative Values
How to Change a Two Dimensional Array to One Dimensional
Pandas Series With Different Lengths
How to Find Consecutive Numbers in a Python List
How to Print a String Multiple Times
How to Copy a File to a Remote Server in Python Using Scp or Ssh
Python Comparing List Values to Keys in List of Dicts
How to Change Border Color in Tkinter Widget
How to Find the Shortest Word in a List in Python
How to Dynamically Build a Json Object
How to Create a for Loop That Goes Through All Diagonal Possibilities of a List
High Pass Filter for Image Processing in Python by Using Scipy/Numpy