Wait-Browser.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function Wait-Browser
{
    <#
    .Synopsis
        Waits for a browser to finish loading
    .Description
        Waits for a browser to finish loading all elements
    .Example
        Open-Browser -Url http://Start-Automating.com -DoNotWait |
            Wait-Browser
    .Link
        Open-Browser
    .Link
        Close-Browser
    #>

    [OutputType([PSObject])]
    param(
    # The Browser Object.
    [Parameter(Mandatory=$true,
        ValueFromPipeline=$true,
        ValueFromPipelineByPropertyName=$true)]
    [ValidateScript({
        if ($_.psobject.typenames -notcontains 'System.__ComObject' -and -not $_.Quit) {
            throw "Not IE"
        }
        $true
    })]
    $IE,
    
    # The timeout to wait for the page to reload after an action
    [Timespan]$Timeout = "0:0:30",
    
    # The timeout to sleep in between each check to see if the page has reloaded
    [Timespan]$SleepTime = "0:0:0.01"
    )
    
    process {
        $start = Get-Date
        
        #region Wait Loop
        while ($Start + $timeout -ge (Get-Date)) {
            if ($ie.Busy) {
                Start-Sleep -Milliseconds $sleepTime.TotalMilliseconds
            }
            
            if ($ie.Document.ReadyState -ne 'Complete') {
                Start-Sleep -Milliseconds $sleepTime.TotalMilliseconds
                continue
            }
            
            $childNodesNotCompleted = $ie.Document.'IHTMLDOMNode_childNodes' | 
                Where-Object {
                    $_.ReadyState -and $_.ReadyState -ne 'Complete'
                }
                
            if ($childNodesNotCompleted) { 
                Start-Sleep -Milliseconds $sleepTime.TotalMilliseconds
                continue
            }
            
            break
        }
        #endregion Wait Loop
        
        #region Did we time out?
        if ($Start + $timeout -lt (Get-Date)) {
            $timedOut = (New-Object TimeoutException)
            Write-Error -Exception $timedOut -ErrorId 'WaitBrowser.Timeout'                        
        }
        #endregion Did we time out?
        $ie                
    }
}