如何在 IE11 中使用 Windows Powershell 注入 JavaScript

How can I inject JavaScript using Windows Powershell with IE11

简单的问题。我正在使用这个:

$links = @("example.com", "example.net", "example.org")
$IE = new-object -com internetexplorer.application
$IE.visible = $true

for($i = 0;$i -lt $links.Count;$i++) {
    $find = $links[$i]
    $IE.navigate2($find)
}

而且我想在循环中使用类似 $IE.addscript("//MyJavaScriptCode") 的东西来将 javascript 代码插入页面上的控制台(或者只是为了 运行)。

我该如何完成上述任务?

谢谢!

让我们谈谈添加脚本。

首先,COM 中没有等待事件。当您 运行 一个操作时,应用程序(在本例中为 IE)将 运行 该操作,因此 powershell 无法知道操作是否已完成。

在这种情况下,让我们谈谈导航。一旦您 运行 命令,您将需要先离开以等待导航完成,然后再继续。

幸运的是我们有 属性 ReadyState。 $IE.Document.ReadyState

我们需要找到等待 ReadyState 等于 Complete

While($IE.Document.readyState -ne 'Complete'){
    sleep -Seconds 1
}

现在是时候添加脚本了。没有直接的方法可以将脚本添加到脚本中。所以我们可以通过 运行ning javascript 添加脚本来解决这个问题。 $IE.Document.Script.execScript(Script Here, Script Type)

我们可以在 Javascript 中创建一个新元素并将该元素附加到头部。在这种情况下,我将使用 Google 的 Jquery Lib

var Script = document.createElement('script');
Script.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js');
document.head.appendChild(Script);

现在,一旦我们添加了脚本,我们就需要等待 IE 将脚本添加到页面,因此我们需要一个短暂的延迟。在这种情况下,我做了 1 秒。

我 运行 通过检查 Jquery 加载的版本 alert($.fn.jquery);

来确保脚本已加载
$JS = @'
var Script = document.createElement('script');
Script.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js');
document.head.appendChild(Script);
'@

$GetVersion = @'
    alert($.fn.jquery);
'@

$links = @("google.com")
$IE = new-object -com internetexplorer.application
$IE.visible = $true
$links | %{
    $Document = $IE.navigate2($_)
    While($IE.Document.readyState -ne 'Complete'){
        sleep -Seconds 1
    }
    $IE.Document.body.getElementsByTagName('body')
    $TEST = $IE.Document.Script.execScript($JS,'javascript')
    sleep -Seconds 1
    $IE.Document.Script.execScript($GetVersion,'javascript')
}