Reputation: 737
Simple question. I'm using this:
$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)
}
And I want to have something like $IE.addscript("//MyJavaScriptCode")
in the loop to insert javascript code to the console on the page (or just so that it is run).
How do I do said task?
Thanks!
Upvotes: 1
Views: 1629
Reputation: 6860
Lets talk about adding scripts.
First thing is there is no waiting for events in COM. When you run a action the application (in this case IE) will run the action, so powershell has no way to know if a action is completed.
In this case lets talk about Navigate. Once you run the command you will need to find away to wait for the nav to finish before you move on.
Lucky we have property ReadyState. $IE.Document.ReadyState
We will need to find away to wait for ReadyState to equal Complete
While($IE.Document.readyState -ne 'Complete'){
sleep -Seconds 1
}
Now its time to add scripts. There is no direct way to add a script to scripts. So we can work around that by running javascript to add a script. $IE.Document.Script.execScript(Script Here, Script Type)
We can create a new element in Javascript and appended that element to the head. In this case ill use Google's 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);
Now once we add the script we need to wait for IE to add the script to page so we need a momentary delay. In this case I did 1 second.
I ran a test to make sure the script loaded by checking the Jquery Version loaded 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')
}
Upvotes: 3