PowerShellから各種ブラウザで開いているURLを取得する (Windows10+Chrome編)

概要

Chrome編です。Chromeは開いているページのURL全部取れないこともないっぽいんですけど、一個あたり1〜2秒くらいかかるので用途によっては厳しい。なんとか減らせないかな?ってTreeWalkerでやってみたけど最短経路で到達しても同じくらいの時間がかかる…。

適当に取れる範囲絞ってとるといいと思う。

ターゲットは「アドレス検索バー」。今回は、ControlTypePropertyで取ってみる。

f:id:harupu:20210322093509p:plain

コード

$chorome_csharp = @"
using System;
using System.Windows.Automation;
using System.Diagnostics;
using System.Collections.Generic;
namespace UIAutomationChrome {
  public class Program {
    public static List<String> GetURLList() {
      List<String> urlList = new List<String>();
      AutomationElementCollection tests = AutomationElement.RootElement.FindAll(TreeScope.Element | TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Pane));
      foreach (AutomationElement testElement in tests){
        AutomationElement test1 = testElement.FindFirst(TreeScope.Element | TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "Chrome_WidgetWin_1"));
        if (test1 == null) {continue;}
        AutomationElement test2 = test1.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
        if (test2 == null ) {continue;}
        ValuePattern v = (ValuePattern)test2.GetCurrentPattern(ValuePattern.Pattern);
        if (v.Current.Value != null && v.Current.Value != "") {
          Console.WriteLine("URL:" + v.Current.Value);
          urlList.Add(v.Current.Value);
        }
      }
      return urlList;
    }
  }
}
"@

Add-Type -TypeDefinition $chorome_csharp -ReferencedAssemblies("UIAutomationClient", "UIAutomationTypes");

foreach ($url in [UIAutomationChromes.Program]::GetURLList()) {
  $url
}

f:id:harupu:20210322093711p:plain