且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IE COM 自动化:如何在 PowerShell 中获取 `window.execScript` 的返回值

更新时间:2022-05-23 22:42:19

首选方法可能是@Matt 建议使用 eval 方法而不是 execScript 已在 IE11 中弃用.但是,我仍然无法找到如何从 IE API 访问该 eval.我创建了另一个问题来跟进.

The preferred method is probably what @Matt suggested to use the eval method instead of execScript which has been deprecated in IE11. However, I still couldn't find how to access that eval from IE API. I created this other question to follow up with that.

然而,我可以想出一种在网页上执行 JavaScript/jQuery 并将结果返回给 PowerShell 的方法,即我们使用 setAttribute 将 JavaScript 返回值存储在 DOM 中,并且然后使用 getAttribute 在 PowerShell 中检索它.

I could, however, figure a way to execute JavaScript/jQuery on a web page and return the results back to PowerShell with this trick that we store the JavaScript return value in the DOM using setAttribute and then retrieving it in PowerShell using getAttribute.

# some web page with jQuery in it
$url = "http://jquery.com/"

# Use this function to run JavaScript on a web page. Your $jsCommand can
# return a value which will be returned by this function unless $global
# switch is specified in which case $jsCommand will be executed in global
# scope and cannot return a value. If you received error 80020101 it means
# you need to fix your JavaScript code.
Function ExecJavaScript($ie, $jsCommand, [switch]$global)
{
    if (!$global) {
        $jsCommand = "document.body.setAttribute('PSResult', (function(){$jsCommand})());"
    }
    $document = $ie.document
    $window = $document.parentWindow
    $window.execScript($jsCommand, 'javascript') | Out-Null
    if (!$global) {
        return $document.body.getAttribute('PSResult')
    }
}

Function CheckJQueryExists
{
    $result = ExecJavaScript $ie 'return window.hasOwnProperty("$");'
    return ($result -eq $true)
}

$ie = New-Object -COM InternetExplorer.Application -Property @{
    Navigate = $url
    Visible = $false
}
do { Start-Sleep -m 100 } while ( $ie.ReadyState -ne 4 )

$jQueryExists = CheckJQueryExists $ie
echo "jQuery exists? $jQueryExists"

# make a jQuery call
ExecJavaScript $ie @'
    // this is JS code, remember to use semicolons
    var content = $('#home-content');
    return content.text();
'@

# Quit and dispose IE COM
$ie.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ie) | out-null
Remove-Variable ie