javascript - 如何使用 Windows Powershell 和 IE11 注入(inject) JavaScript

标签 javascript powershell internet-explorer-11

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

$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
}

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

我们可以在 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')
}

关于javascript - 如何使用 Windows Powershell 和 IE11 注入(inject) JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54504553/

相关文章:

PowerShell -gt 比较运算符不起作用

html - Bootstrap 列在 IE11 (Flex) 中不起作用

javascript - 在 Javascript 为什么 -'54' +30 的结果是 -24(在 javascript 中类型强制)

javascript - 瓦片层加载开始和结束时的传单触发事件

powershell - 按共性分组

javascript - 如何在 Internet Explorer 11 中获取 RadioNodeList 值?

Angular 元素输出在 IE11 中不起作用

javascript - 替换使用 ajax 的页面上的内容

javascript - 如何添加标签 <html :submit> dynamically?

powershell - 如何使用通配符在子目录中查找文件