03-24-2024, 07:25 AM
// script "Chrome switch to tab by URL.cs"
//example
print.clear();
var r = Chrome.ActivateTabByURL("*libreautomate.com*") ?? throw new NotFoundException();
print.it(r.url);
class Chrome {
/// <summary>
/// Finds Chrome tab by URL, and activates it.
/// Searches in all Chrome windows.
/// </summary>
/// <param name="url">URL. Format: wildcard expression.</param>
/// <param name="activateWindow">Activete the Chrome window. Default true.</param>
/// <returns>Tab info; null if not found.</returns>
/// <exception cref="Exception">Something failed.</exception>
/// <remarks>
/// Temporarily activates each tab (to get its URL) until finds the specified tab. There is no way to avoid it; even Selenium cannot get URL of inactive tabs.
/// </remarks>
public static ATBUResult ActivateTabByURL(string url, bool activateWindow = true) {
wildex wx = url;
foreach (var w in wnd.findAll("*Google Chrome", "Chrome_WidgetWin_1")) {
if (_ATBU_Window(w, wx, activateWindow) is { } r) return r;
}
return null;
}
/// <summary>
/// Finds Chrome tab by URL, and activates it.
/// </summary>
/// <param name="wChrome">Chrome window.</param>
/// <param name="url">URL. Format: wildcard expression.</param>
/// <param name="activateWindow">Activete the Chrome window. Default true.</param>
/// <returns>Tab info; null if not found.</returns>
/// <exception cref="Exception">Something failed.</exception>
/// <remarks>
/// Temporarily activates each tab (to get its URL) until finds the specified tab. There is no way to avoid it; even Selenium cannot get URL of inactive tabs.
/// </remarks>
public static ATBUResult ActivateTabByURL(wnd wChrome, string url, bool activateWindow = true) => _ATBU_Window(wChrome, url, activateWindow);
static ATBUResult _ATBU_Window(wnd w, wildex wx, bool activateWindow) {
var tablist = w.Elm["PAGETABLIST"].Find(-1);
var tabs = tablist?.Elm["PAGETAB"].FindAll();
if (tabs?.Any() == true) {
var currentTab = tabs.FirstOrDefault(o => o.IsSelected);
foreach (var tab in tabs) {
tab.Invoke();
var doc = w.Elm["web:DOCUMENT", prop: "value=?*"].Find(5);
var u = doc.Value;
if (wx.Match(u)) {
if (activateWindow) w.Activate();
return new(w, tab, doc, u);
}
}
currentTab?.Invoke();
}
return null;
}
public record class ATBUResult(wnd window, elm tabButton, elm document, string url);
}