GPAL - Generally Positive Automation Library v1.0
GPAL The Fluent Automation LIbrary
Loading...
Searching...
No Matches
GenerallyPositive.Browser.BrowserHelper Class Reference

Classes

class  KillProcessesResult
 Result of attempting to kill one or more processes by name. More...

Static Public Member Functions

static IWebDriver GetBrowserDriver (BrowserSettings browserSettings)
 Create (or return the existing) Selenium WebDriver for the given BrowserSettings.
Configures Chrome, Edge or Firefox options (profile, headless, download, stealth, debugging), starts the driver, navigates to the configured URL and waits for document ready.
static void AllowDownloads (BrowserSettings browserSettings, string directory)
 Accept downloads into directory without asking where to put them, whatever the profile says.
This is the same CDP command SetHeadlessDownload uses, and it is the reason headless has always downloaded quietly while a windowed browser still put up a Save dialog: headless got this call and windowed was left relying on download.prompt_for_download in the profile, which a supplied or pre-existing profile can override. No filename here, only the directory, because this sets the default for every download rather than naming one.
Chromium only, and callers are expected to know that. Firefox has no CDP and does not need one, since its own download preferences are set when the driver is built.
static void SetHeadlessDownload (BrowserSettings browserSettings, string destination)
 Instructs the underlying Chromium driver (via CDP Page.setDownloadBehavior) to send the next download to the directory of destination , which is the directory the download watcher is sitting on.
This runs for every download the watcher is waiting on, not only headless ones. Setting it per download keeps the profile out of it, so a stale download.default_directory in a supplied profile cannot send the file somewhere nobody is looking.
Chromium only, and it says nothing when it is not. Firefox has no CDP, is pointed at its download directory when the driver is built, and has its download watcher put on that directory rather than on the destination - so there is nothing here it is missing out on and nothing for anyone to act on.
static string SeleniumAddScriptToEvaluateOnNewDocument (BrowserSettings browserSettings, string script)
static void SeleniumRemoveScriptToEvaluateOnNewDocument (BrowserSettings browserSettings, string identifier)
 Removes a script previously registered via SeleniumAddScriptToEvaluateOnNewDocument, using the Selenium Chromium CDP command Page.removeScriptToEvaluateOnNewDocument. Chrome/Edge only.
static string GetBrowserProfileDirectory (BrowserSettings browserSettings, bool getDefaultDirectory=false)
 Get the browserSettings.ProfileUserName profile directory under the default user directory.
static string FindProfileDirectory (string userDataDirectory, string profileName)
 the profile name might not be what we expect, which is a directory name. this will iterate thru all directories under user-data-dir, open the Preferences file and try to match token profile.name if it matches, then the directory containing that Preferences file is returned
static string FindFirefoxBinaryLocation ()
 Looks up the installed Firefox executable path from the registry key configured in GPAL.GPALSettings.FirefoxBinaryPathRegistry.
static string FindTab (BrowserSettings browserSettings, string URL)
 Searches all open browser window handles for one whose URL matches (or is matched by) URL , switching the driver's focus to that window if found.
static bool GotoNextPage (Browser browser)
 Navigates to the next page of results, either by clicking/following the configured "next page" selector (or its href, if any), or, when InfiniteScroll is enabled, by scrolling to the bottom of the page and waiting for new content to load.
static void FillInWithTokens (Browser browser, IGPALGrid< string > tokens, WriteMode writeMode)
 Finds the elements matching the unit of work's selectors, arranges them into a grid of rows and columns, and fills each editable element with the corresponding token from tokens using writeMode (Overwrite, Insert or Append).
If more rows of tokens remain than were consumed, invokes CallAfterFillIn (if set) and repeats for the next page/iteration until all tokens have been consumed.
static void CheckDocumentReady (Browser browser, bool overrideSetting=false)
static object ExecuteJavaScriptObj (string executeMe, IBrowser browser, params object[] args)
static string ExecuteJavaScript (IBrowser browser, string executeMe, params object[] args)
 Runs a script and hands back what it produced.

Selenium's executor is a function body, so it needs a return to give a value back. OttoMagic and Puppeteer evaluate a statement list and answer with the value of its last statement, the way eval does, so a return there has nothing to return from and V8 refuses it. A script written either way works on all three: one written the second way already does, and one written the first way is put inside a function and run again, where the return is legal and the value comes back unchanged.

The engine is what says the return was illegal. Nothing here reads the script.
static string GetCurrentUrl (BrowserSettings browserSettings)
 Returns the current page URL, queried via OttoMagic, Puppeteer, or the Selenium WebDriver depending on the browser's automation engine.
static string JsCheckReadyState (dynamic browser, string sessionToken)
 Use javascript to check the page document.ready state, only called from one place that does the timing checks While only used in GPAL for Selenium checking, it is defensively coded to handle all Automation Engines.
static void SeleniumGoToUrl (GPALUrl url, BrowserSettings browserSettings)
 Navigates the Selenium WebDriver to url and inspects the browser's performance logs (Network.responseReceived events) to determine the HTTP status code of the navigation, storing it in browserSettings.ServerResponseCode (0 if no status could be determined, -1 on error).
static KillProcessesResult KillProcessesByName (params string[] namesOfProcessesToKill)
 Kills all running processes whose name matches any of namesOfProcessesToKill .
static string GetUserAgent (IBrowser browser)
 Test the url to determine whether it is a PDF file by.
static bool TestUrlForPDF (Browser browser, string url)
 checking the extension of the url, but also calling the URL to see if it returns a pdf response header GPAL calls this if we don't detect a file downloaded but expect one
static bool DownloadPdfFile (string pdfUrl, string savePath, IBrowser browser)
static KillProcessesResult[] KillAllRunningWebDrivers ()
 Kills all known webdriver processes (geckodriver, chromedriver, IEDriverServer, MSEdgeDriver) and resets the "already updating" driver-update flag.
static KillProcessesResult[] KillAllRunningProcesses (bool killWebDrivers, IBrowser browser)
static KillProcessesResult KillProcess (Process process)
 Kill the process (browser launched by MagicHelper or puppeteer.
static KillProcessesResult KillProcess (string processName)
 Kills all running processes with the given name, waiting for each to exit.
static string RestApiLocation ()
 Where GPALRestAPI is installed, worked out the way the browser works it out: a registry key names the host manifest, and the manifest names the exe. Nothing has to be running for this to answer.
static int LiveRestApiHosts (out List<(int processId, int port)> hosts)
 Every GPALRestAPI running on this machine right now, as the process that hosts it and the port it listens on. Each host writes its own line and takes it back out on the way down, so what comes back is what is up.

OttoMagic only. A GPALRestAPI is started by the browser extension, so Selenium and Puppeteer have none and a run on those engines finds nothing here. That is not a failure, it is the answer.

One OttoMagic browser is one host, so this is the mapping a workflow driving several of them has no other way to see: Browser.RestApiBaseUrl tells a browser its own port and nothing tells it about the others. A run can check that as many came up as were asked for, and name the one that did not.
static void TopBrowser (Browser browser, bool moveDontClick, bool forceClick=false)
static bool WaitForNetworkIdle (Browser browser, string sessionToken)
 Polls a custom javascript network monitor (window.__gpalNetworkMonitor) until there are 0 in-flight requests for browserSettings.NetworkIdlePruneMs continuous milliseconds, or until browserSettings.NetworkIdleTimeoutMs is exceeded.
static bool WaitForNetworkIdle (Browser browser, int timeoutMs=500, int maxConnections=0, int pruneMs=3000, string sessionToken=null)
 OttoMagic (RESTClient/GPALRestAPI) variant of network-idle detection: repeatedly calls the CheckNetworkIdle endpoint until it reports "idle" or timeoutMs elapses.
static IPEndPoint[] GetAllTcpListeners ()
 Returns all active TCP listener endpoints on this machine.
static bool IsPortListening (int port)
 Checks whether anything is currently listening on the given TCP port.

Detailed Description

Definition at line 56 of file BrowserHelper.cs.

Member Function Documentation

◆ AllowDownloads()

void GenerallyPositive.Browser.BrowserHelper.AllowDownloads ( BrowserSettings browserSettings,
string directory )
static

Accept downloads into directory without asking where to put them, whatever the profile says.
This is the same CDP command SetHeadlessDownload uses, and it is the reason headless has always downloaded quietly while a windowed browser still put up a Save dialog: headless got this call and windowed was left relying on download.prompt_for_download in the profile, which a supplied or pre-existing profile can override. No filename here, only the directory, because this sets the default for every download rather than naming one.
Chromium only, and callers are expected to know that. Firefox has no CDP and does not need one, since its own download preferences are set when the driver is built.

Parameters
browserSettingsBrowserSettings for a Chrome or Edge browser
directoryDirectory downloads should land in

Definition at line 555 of file BrowserHelper.cs.

◆ CheckDocumentReady()

void GenerallyPositive.Browser.BrowserHelper.CheckDocumentReady ( Browser browser,
bool overrideSetting = false )
static

Definition at line 1447 of file BrowserHelper.cs.

◆ DownloadPdfFile()

bool GenerallyPositive.Browser.BrowserHelper.DownloadPdfFile ( string pdfUrl,
string savePath,
IBrowser browser )
static

Definition at line 2444 of file BrowserHelper.cs.

◆ ExecuteJavaScript()

string GenerallyPositive.Browser.BrowserHelper.ExecuteJavaScript ( IBrowser browser,
string executeMe,
params object[] args )
static

Runs a script and hands back what it produced.

Selenium's executor is a function body, so it needs a return to give a value back. OttoMagic and Puppeteer evaluate a statement list and answer with the value of its last statement, the way eval does, so a return there has nothing to return from and V8 refuses it. A script written either way works on all three: one written the second way already does, and one written the first way is put inside a function and run again, where the return is legal and the value comes back unchanged.

The engine is what says the return was illegal. Nothing here reads the script.

Parameters
browserBrowser to run the script in
executeMeThe script
argsArguments the script refers to, where the engine supports them
Returns
What the script produced

Definition at line 1980 of file BrowserHelper.cs.

◆ ExecuteJavaScriptObj()

object GenerallyPositive.Browser.BrowserHelper.ExecuteJavaScriptObj ( string executeMe,
IBrowser browser,
params object[] args )
static

Definition at line 1860 of file BrowserHelper.cs.

◆ FillInWithTokens()

void GenerallyPositive.Browser.BrowserHelper.FillInWithTokens ( Browser browser,
IGPALGrid< string > tokens,
WriteMode writeMode )
static

Finds the elements matching the unit of work's selectors, arranges them into a grid of rows and columns, and fills each editable element with the corresponding token from tokens using writeMode (Overwrite, Insert or Append).
If more rows of tokens remain than were consumed, invokes CallAfterFillIn (if set) and repeats for the next page/iteration until all tokens have been consumed.

Parameters
browserBrowser whose CurrentUOW selectors are used to locate the input elements
tokensGrid (rows of columns) of string values to fill into the matched elements
writeModeHow to write each token: Overwrite, Insert or Append

Definition at line 1129 of file BrowserHelper.cs.

◆ FindFirefoxBinaryLocation()

string GenerallyPositive.Browser.BrowserHelper.FindFirefoxBinaryLocation ( )
static

Looks up the installed Firefox executable path from the registry key configured in GPAL.GPALSettings.FirefoxBinaryPathRegistry.

Returns
Full path to firefox.exe, or null if Firefox is not installed/registered

Definition at line 992 of file BrowserHelper.cs.

◆ FindProfileDirectory()

string GenerallyPositive.Browser.BrowserHelper.FindProfileDirectory ( string userDataDirectory,
string profileName )
static

the profile name might not be what we expect, which is a directory name. this will iterate thru all directories under user-data-dir, open the Preferences file and try to match token profile.name if it matches, then the directory containing that Preferences file is returned

Parameters
userDataDirectory
profileName
Returns
The directory for profileName

Definition at line 939 of file BrowserHelper.cs.

◆ FindTab()

string GenerallyPositive.Browser.BrowserHelper.FindTab ( BrowserSettings browserSettings,
string URL )
static

Searches all open browser window handles for one whose URL matches (or is matched by) URL , switching the driver's focus to that window if found.

Parameters
browserSettingsBrowserSettings whose driver's windows are searched
URLURL (or partial URL) to look for among the open tabs
Returns
The window handle of the matching tab, or null if no tab matches

Definition at line 1015 of file BrowserHelper.cs.

◆ GetAllTcpListeners()

IPEndPoint[] GenerallyPositive.Browser.BrowserHelper.GetAllTcpListeners ( )
static

Returns all active TCP listener endpoints on this machine.

Returns
Array of IPEndPoint for every active TCP listener

Definition at line 4082 of file BrowserHelper.cs.

◆ GetBrowserDriver()

IWebDriver GenerallyPositive.Browser.BrowserHelper.GetBrowserDriver ( BrowserSettings browserSettings)
static

Create (or return the existing) Selenium WebDriver for the given BrowserSettings.
Configures Chrome, Edge or Firefox options (profile, headless, download, stealth, debugging), starts the driver, navigates to the configured URL and waits for document ready.

Parameters
browserSettingsBrowserSettings describing how to launch and configure the browser
Returns
The IWebDriver for the browser, or the existing driver if already set

chrome 136+ requires a user data dir to do anything with cdp port, so define first cause it has to be in place to query useragent

Definition at line 71 of file BrowserHelper.cs.

◆ GetBrowserProfileDirectory()

string GenerallyPositive.Browser.BrowserHelper.GetBrowserProfileDirectory ( BrowserSettings browserSettings,
bool getDefaultDirectory = false )
static

Get the browserSettings.ProfileUserName profile directory under the default user directory.

Parameters
browserSettingsBrowserSettings object
getDefaultDirectoryignore browserSettings.ProfileUserName and return the default profile directory alone
Returns

Definition at line 892 of file BrowserHelper.cs.

◆ GetCurrentUrl()

string GenerallyPositive.Browser.BrowserHelper.GetCurrentUrl ( BrowserSettings browserSettings)
static

Returns the current page URL, queried via OttoMagic, Puppeteer, or the Selenium WebDriver depending on the browser's automation engine.

Parameters
browserSettingsBrowserSettings of the browser to query
Returns
The current page URL

Definition at line 2044 of file BrowserHelper.cs.

◆ GetUserAgent()

string GenerallyPositive.Browser.BrowserHelper.GetUserAgent ( IBrowser browser)
static

Test the url to determine whether it is a PDF file by.

Returns the live user agent string actually presented by the browser's active automation engine (OttoMagic, Puppeteer, or Selenium), as opposed to MagicHelper.GetUserAgentString which returns a templated user agent built from the locally installed browser version.
Used by TestUrlForPDF and DownloadPdfFile so that out-of-band HttpClient requests present the same User-Agent header as the browser itself.

Parameters
browserBrowser to query
Returns
The live user agent string, or a templated fallback if it could not be determined

Definition at line 2318 of file BrowserHelper.cs.

◆ GotoNextPage()

bool GenerallyPositive.Browser.BrowserHelper.GotoNextPage ( Browser browser)
static

Navigates to the next page of results, either by clicking/following the configured "next page" selector (or its href, if any), or, when InfiniteScroll is enabled, by scrolling to the bottom of the page and waiting for new content to load.

Parameters
browserBrowser to navigate
Returns
True if the next page action (click or scroll) was performed, false if no next page button was found

Definition at line 1035 of file BrowserHelper.cs.

◆ IsPortListening()

bool GenerallyPositive.Browser.BrowserHelper.IsPortListening ( int port)
static

Checks whether anything is currently listening on the given TCP port.

Parameters
portPort number to check
Returns
True if a TCP listener is active on the port, false otherwise
GPAL.PublishSimpleEvent(GPALEventType.INFO, "CDP debug port already in use.");
static bool IsPortListening(int port)
Checks whether anything is currently listening on the given TCP port.
Everything starts here, all the GPAL controls and global settings using fluent syntax are here....
Definition GPAL.cs:49
static void PublishSimpleEvent(GPALEventType gPALEventType, string msg, dynamic gPALObject=null, Enums.GPALObjectType gPALObjectType=GPALObjectType.None, Exception ex=null)
Publish a message to either the information channel or exception channel (if exception passed in) Pub...
Definition GPAL.cs:2406

Definition at line 4098 of file BrowserHelper.cs.

◆ JsCheckReadyState()

string GenerallyPositive.Browser.BrowserHelper.JsCheckReadyState ( dynamic browser,
string sessionToken )
static

Use javascript to check the page document.ready state, only called from one place that does the timing checks While only used in GPAL for Selenium checking, it is defensively coded to handle all Automation Engines.

Parameters
browser
timeOutInMs
Returns

Definition at line 2070 of file BrowserHelper.cs.

◆ KillAllRunningProcesses()

KillProcessesResult[] GenerallyPositive.Browser.BrowserHelper.KillAllRunningProcesses ( bool killWebDrivers,
IBrowser browser )
static

Definition at line 2767 of file BrowserHelper.cs.

◆ KillAllRunningWebDrivers()

KillProcessesResult[] GenerallyPositive.Browser.BrowserHelper.KillAllRunningWebDrivers ( )
static

Kills all known webdriver processes (geckodriver, chromedriver, IEDriverServer, MSEdgeDriver) and resets the "already updating" driver-update flag.

Returns
An array of KillProcessesResult, one per webdriver process name attempted

Definition at line 2668 of file BrowserHelper.cs.

◆ KillProcess() [1/2]

KillProcessesResult GenerallyPositive.Browser.BrowserHelper.KillProcess ( Process process)
static

Kill the process (browser launched by MagicHelper or puppeteer.

Parameters
process

Definition at line 2975 of file BrowserHelper.cs.

◆ KillProcess() [2/2]

KillProcessesResult GenerallyPositive.Browser.BrowserHelper.KillProcess ( string processName)
static

Kills all running processes with the given name, waiting for each to exit.

Parameters
processNameProcess name to kill (without .exe)
Returns
A KillProcessesResult describing how many matching processes were found and killed
BrowserHelper.KillProcess("GPALRestAPI");
static KillProcessesResult KillProcess(Process process)
Kill the process (browser launched by MagicHelper or puppeteer.

Definition at line 3013 of file BrowserHelper.cs.

◆ KillProcessesByName()

KillProcessesResult GenerallyPositive.Browser.BrowserHelper.KillProcessesByName ( params string[] namesOfProcessesToKill)
static

Kills all running processes whose name matches any of namesOfProcessesToKill .

Parameters
namesOfProcessesToKillOne or more process names to kill (without .exe)
Returns
The result of killing the last process name in the list
BrowserHelper.KillProcessesByName("chromedriver", "msedgedriver");
static KillProcessesResult KillProcessesByName(params string[] namesOfProcessesToKill)
Kills all running processes whose name matches any of namesOfProcessesToKill .

Definition at line 2298 of file BrowserHelper.cs.

◆ LiveRestApiHosts()

int GenerallyPositive.Browser.BrowserHelper.LiveRestApiHosts ( out List<(int processId, int port)> hosts)
static

Every GPALRestAPI running on this machine right now, as the process that hosts it and the port it listens on. Each host writes its own line and takes it back out on the way down, so what comes back is what is up.

OttoMagic only. A GPALRestAPI is started by the browser extension, so Selenium and Puppeteer have none and a run on those engines finds nothing here. That is not a failure, it is the answer.

One OttoMagic browser is one host, so this is the mapping a workflow driving several of them has no other way to see: Browser.RestApiBaseUrl tells a browser its own port and nothing tells it about the others. A run can check that as many came up as were asked for, and name the one that did not.

Parameters
hostsProcess id and port for each running GPALRestAPI, empty when none are.
Returns
How many were found.

Definition at line 3159 of file BrowserHelper.cs.

◆ RestApiLocation()

string GenerallyPositive.Browser.BrowserHelper.RestApiLocation ( )
static

Where GPALRestAPI is installed, worked out the way the browser works it out: a registry key names the host manifest, and the manifest names the exe. Nothing has to be running for this to answer.

Returns
Full path to GPALRestAPI.exe, or null when the host is not registered.

Definition at line 3104 of file BrowserHelper.cs.

◆ SeleniumAddScriptToEvaluateOnNewDocument()

string GenerallyPositive.Browser.BrowserHelper.SeleniumAddScriptToEvaluateOnNewDocument ( BrowserSettings browserSettings,
string script )
static

Definition at line 851 of file BrowserHelper.cs.

◆ SeleniumGoToUrl()

void GenerallyPositive.Browser.BrowserHelper.SeleniumGoToUrl ( GPALUrl url,
BrowserSettings browserSettings )
static

Navigates the Selenium WebDriver to url and inspects the browser's performance logs (Network.responseReceived events) to determine the HTTP status code of the navigation, storing it in browserSettings.ServerResponseCode (0 if no status could be determined, -1 on error).

Parameters
urlURL to navigate to
browserSettingsBrowserSettings of the browser to navigate, used to read performance logs and store the resulting status code

Definition at line 2135 of file BrowserHelper.cs.

◆ SeleniumRemoveScriptToEvaluateOnNewDocument()

void GenerallyPositive.Browser.BrowserHelper.SeleniumRemoveScriptToEvaluateOnNewDocument ( BrowserSettings browserSettings,
string identifier )
static

Removes a script previously registered via SeleniumAddScriptToEvaluateOnNewDocument, using the Selenium Chromium CDP command Page.removeScriptToEvaluateOnNewDocument. Chrome/Edge only.

Parameters
browserSettingsBrowserSettings for the browser to remove the script from
identifierThe CDP script identifier returned by SeleniumAddScriptToEvaluateOnNewDocument

Definition at line 873 of file BrowserHelper.cs.

◆ SetHeadlessDownload()

void GenerallyPositive.Browser.BrowserHelper.SetHeadlessDownload ( BrowserSettings browserSettings,
string destination )
static

Instructs the underlying Chromium driver (via CDP Page.setDownloadBehavior) to send the next download to the directory of destination , which is the directory the download watcher is sitting on.
This runs for every download the watcher is waiting on, not only headless ones. Setting it per download keeps the profile out of it, so a stale download.default_directory in a supplied profile cannot send the file somewhere nobody is looking.
Chromium only, and it says nothing when it is not. Firefox has no CDP, is pointed at its download directory when the driver is built, and has its download watcher put on that directory rather than on the destination - so there is nothing here it is missing out on and nothing for anyone to act on.

Parameters
browserSettingsBrowserSettings for the browser performing the download
destinationFull path (directory + filename) to allow the download to be written to

Definition at line 757 of file BrowserHelper.cs.

◆ TestUrlForPDF()

bool GenerallyPositive.Browser.BrowserHelper.TestUrlForPDF ( Browser browser,
string url )
static

checking the extension of the url, but also calling the URL to see if it returns a pdf response header GPAL calls this if we don't detect a file downloaded but expect one

Parameters
urlthe url of the potential pdf file
Returns
true or false

Definition at line 2357 of file BrowserHelper.cs.

◆ TopBrowser()

void GenerallyPositive.Browser.BrowserHelper.TopBrowser ( Browser browser,
bool moveDontClick,
bool forceClick = false )
static

Definition at line 3217 of file BrowserHelper.cs.

◆ WaitForNetworkIdle() [1/2]

bool GenerallyPositive.Browser.BrowserHelper.WaitForNetworkIdle ( Browser browser,
int timeoutMs = 500,
int maxConnections = 0,
int pruneMs = 3000,
string sessionToken = null )
static

OttoMagic (RESTClient/GPALRestAPI) variant of network-idle detection: repeatedly calls the CheckNetworkIdle endpoint until it reports "idle" or timeoutMs elapses.

Parameters
timeoutMsMaximum time to wait for network idle, in milliseconds
maxConnectionsMaximum number of in-flight connections still considered "idle"
pruneMsHow long the connection count must stay at or below maxConnections to be considered idle
sessionTokenToken used to suppress repeated log messages within the same wait session
Returns
True if the network reached idle before the timeout, false otherwise

Definition at line 4004 of file BrowserHelper.cs.

◆ WaitForNetworkIdle() [2/2]

bool GenerallyPositive.Browser.BrowserHelper.WaitForNetworkIdle ( Browser browser,
string sessionToken )
static

Polls a custom javascript network monitor (window.__gpalNetworkMonitor) until there are 0 in-flight requests for browserSettings.NetworkIdlePruneMs continuous milliseconds, or until browserSettings.NetworkIdleTimeoutMs is exceeded.

Parameters
browserBrowser to monitor
sessionTokenToken used to suppress repeated log messages within the same wait session
Returns
True if the network reached idle before the timeout, false otherwise

Definition at line 3840 of file BrowserHelper.cs.


The documentation for this class was generated from the following file: