Friday, February 3, 2017

loop through chrome tabs and close page depending on web address

Leave a Comment

I would like to be able to loop through all the tabs on a chrome page and close any tabs which are youtube pages.

I have done some googling & found the code below. There are two (well probably more) issues. Firstly I have create a WPF application and added the System.Windows.Automation namespace (using visual studio 2015 .net 4.5) but AutomationElement is not recognised.

Also I am unsure of how to loop through the tabs and test if a page is a youtube page.

        Process[] procsChrome = Process.GetProcessesByName("chrome");          if (procsChrome.Length <= 0)             return null;          foreach (Process proc in procsChrome)         {             // the chrome process must have a window              if (proc.MainWindowHandle == IntPtr.Zero)                 continue;              // to find the tabs we first need to locate something reliable - the 'New Tab' button              AutomationElement root = AutomationElement.FromHandle(proc.MainWindowHandle);             var SearchBar = root.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Address and search bar"));             if (SearchBar != null)             {                 AutomationPattern[] patterns = SearchBar.GetSupportedPatterns();                 if(patterns.Length > 0)                 {                     ValuePattern val = (ValuePattern)SearchBar.GetCachedPattern(patterns[0]);                     if (val.Current.Value.Contains("youtube.com") || val.Current.Value.Contains("youtube.co.uk"))                         proc.Close();                 }             }          } 

5 Answers

Answers 1

System.Windows.Automation is in UIAutomationClient.dll.Did you add UIAutomationClient.dll as a reference to your project?

Check for value "youtube".

if (SearchBar != null)  {     AutomationPattern[] patterns = SearchBar.GetSupportedPatterns();     if (patterns.Length > 0)      {         ValuePattern val = (ValuePattern)SearchBar.GetCurrentPattern(patterns[0]);         if(val.Current.Value.Contains("youtube.com"))             proc.Close();     } } 

Answers 2

Based on your question, I wrote a small program to achieve this. Let me know if it works.

using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Threading; class Program {      [DllImport("user32.dll")]     static extern bool SetForegroundWindow(IntPtr hWnd);      [DllImport("user32.dll")]     static extern bool IsIconic(IntPtr hWnd);      [DllImport("user32.dll")]     static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);      static void Main()     {         Process[] procs = Process.GetProcessesByName("chrome");          if (procs.Length == 0)         {             Console.WriteLine("Google Chrome is not currently open");             return;         }          List<string> titles = new List<string>();          IntPtr hWnd = IntPtr.Zero;         int id = 0;         int numTabs = procs.Length;          foreach (Process p in procs)         {             if (p.MainWindowTitle.Length > 0)             {                 hWnd = p.MainWindowHandle;                 id = p.Id;                 break;             }         }          bool isMinimized = IsIconic(hWnd);          if (isMinimized)         {             ShowWindow(hWnd, 9); // restore             Thread.Sleep(100);         }          SetForegroundWindow(hWnd);         SendKeys.SendWait("^1"); // change focus to first tab         Thread.Sleep(100);          int next = 1;         string title;          while (next <= numTabs)         {             try             {                 title = Process.GetProcessById(id).MainWindowTitle.Replace(" - Google Chrome", "");                 if (title.ToLower().Contains("youtube"))                 {                     SendKeys.SendWait("^{w}"); // close tab.                     Thread.Sleep(100);                 }                 next++;                 SendKeys.SendWait("^{TAB}"); // change focus to next tab                 Thread.Sleep(100);             }             catch (Exception ex)             {                 // Chrome internal process, doesn't have tab.              }                        }          if (isMinimized)         {             ShowWindow(hWnd, 6); // minimize again             Thread.Sleep(100);         }          hWnd = Process.GetCurrentProcess().MainWindowHandle;         SetForegroundWindow(hWnd);         Thread.Sleep(100);          Console.WriteLine("Closed youtube tabs");          Console.ReadKey();     }  } 

Answers 3

Killing just Chrome tabs with YouTube doesn't really seem like a solution to the actual problem here. I think it would fair easier and more reliable to force all the workstations to go to sleep.

Something from this post ought to do the trick. rundll32.exe powrprof.dll,SetSuspendState 0,1,0 perhaps?

Answers 4

It can be done easily with AutoHotkey

Here is a script that will open Chrome, loop all tabs and close the YouTube ones, then minimize Chrome again

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases. ; #Warn  ; Enable warnings to assist with detecting common errors. SendMode Input  ; Recommended for new scripts due to its superior speed and reliability. SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.  SetTitleMatchMode, 2   IfWinExist, ahk_class Chrome_WidgetWin_1 {     WinActivate, Chrome     WinGetActiveTitle, ActiveWindowOld     Loop {         Send, ^{Tab}         Sleep, 500         WinGetActiveTitle, ActiveWindow         if (ActiveWindow = ActiveWindowOld)         {             break         }         IfInString, ActiveWindow, YouTube - Google Chrome         {             Send, ^{w}         }     }     WinMinimize, Chrome } 

Credit: https://autohotkey.com/board/topic/148742-cycling-through-all-chrome-tabs-and-closing-a-specific-tab/

Answers 5

if (SearchBar != null) {     bool valuePatternExist = (bool)SearchBar.GetCurrentPropertyValue(AutomationElement.IsValuePatternAvailableProperty);     if (valuePatternExist)     {         ValuePattern val = SearchBar.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;         if (val.Current.Value.Contains("youtube.com") || val.Current.Value.Contains("youtube.co.uk"))             proc.Close();     } } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment