Dim bot As Selenium.ChromeDriver
Public Sub WebTest()
Set bot = New Selenium.ChromeDriver
Dim kys As New SeleniumWrapper.keys, arr(), i As Long
arr = Application.Transpose(Selection)
With bot
.Get "https://www.gandhi.com.mx/", -1, True
For i = LBound(arr) To UBound(arr)
If Not IsEmpty(arr(i)) Then
If i > 1 Then
.ExecuteScript "window.open('https://www.gandhi.com.mx/')"
End If
.FindElementByCss("[name=q]").SendKeys arr(i)
.SendKeys bot.keys.Enter
End If
Next
End With
Application.SendKeys "{NUMLOCK}", True
MsgBox "Completed"
End Sub
This is the whole code and i'm assigning the same to a button in excel. The code works fine while opening two or three chrome tabs and shows the below error.
javascript error
javascript error: illegal invocation
I have tried using Application.SendKeys ("^t") and its working. But I could not navigate to any other window while my macro running. If I navigate Ctrl+t works on that application. And i'm getting WindowNotFound Error.
And also I tried using webdriver to open new chrome tab as shown below and it doesn't work.
bot.SendKeys kys.Control, "t"
Related
I'm trying to figure out if I can automate the following tasks,
Open the IE
Navigate to a site
Enter login and password
From the user page - Search XXX
Right click on the returned result
From the drop down menu Left click save
Save to a designated folder
I need to repeat this task for 500 times, what's the best way to go about it? I'm thinking of creating a VB Script but not sure if I can do all above with it..
I also found that this can be done in javascript as well? but I don't even know where to start from.
Can someone please give me the right direction? thanks,
1) Yes, you can do it with the Windows Script Host using VBScript or JScript (doesn't matter), using the InternetExplorer.Application COM object.
For details, check this thread: Vbscript for automated website login testing
See also the MSDN documentation about the IE object model: https://msdn.microsoft.com/en-us/library/ms970456.aspx
VBScript example by Francis MacDonald copied from the other thread:
Dim IE
Dim Helem
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = 1
IE.navigate "http://www.example.com"
Set Helem = IE.document.getElementByID("formUsername")
Helem.Value = "username" ' change this to yours
Set Helem = IE.document.getElementByID("formPassword")
Helem.Value = "password" ' change this to yours
Set Helem = IE.document.Forms(0)
Helem.Submit
Do While (IE.Busy)
WScript.Sleep 10
Loop
Dim someElement
Set someElement = IE.document.getElementByID("someElement")
If Len(someElement.innerText) > 0 Then
MsgBox "logged in"
End If
2) There is a tool designed specifically for this task which may help you further: Selenium.
I'm developing an app which has to:
Open a webpage in a Webview;
Check the available links and click on the link which contains a certain word (I.e. http://www.domain.com/myword); after the click, the link will open in the same webview.
I tried the following code but it' giving this error "E/Web Console(6169): Uncaught SyntaxError: Unexpected identifier at null:1".
WebSettings myBrowserSettings = myBrowser.getSettings();
myBrowserSettings.setJavaScriptEnabled(true);
Log.d("Stefano", "JS enabled");
myBrowser.loadUrl("javascript:document.getElementsByTagName('a[href*='myWord']')[0].click();");
Can you help me?
Consider that I'm using document.getElementsById('My ID') in another part of the app (to click a button) and it's working correctly; but here, i'm not able to get getElementsByTagName working.
Thanks for your time and availability
UPDATE:
I replaced 'a[href*='myWord']' with \"a[href*='myWord']\" as suggested by the user but now i have this error E/Web Console(2683): Uncaught TypeError: Cannot call method 'click' of undefined at null:1.
Any idea?
'a[href*='myWord']'
This reads as string 'a[href*=', var myWord, string ']'
Presumably, you are trying to do this:
\"a[href*='myWord']\"
I'm trying to test a popup page with chrome webdriver and selenium2 using .NET, but I'm having issues. I need to change the value of an element after it's window pops up. I need to chage the default "selectedIndexes":["1"]" to "selectedIndexes":["0"]"
The element is:
<input id="tsTabs_ClientState" name="tsTabs_ClientState" type="hidden" autocomplete="off"
value="{"selectedIndexes":["1"], "logEntries":[], "scrollState":{}}">
My code is as follows:
(I've tried both below listed ExecuteScript lines)
Dim chromeDriver = New ChromeDriver("C:\clearcase\Projects\CMS\VbSeTest")
Try
'Chrome Test
chromeDriver.Navigate().GoToUrl("http://localhost/CMS/<location>.aspx")
Dim queryC As IWebElement = chromeDriver.FindElement(By.Id("ctl00_cphM_grd_ctl00_ctl02_ctl00_ACI_btnInitInsert"))
queryC.Click()
Dim current As String = chromeDriver.CurrentWindowHandle
Dim windows = chromeDriver.WindowHandles.AsEnumerable
Dim addOrgWindow As IWebDriver
For Each window In windows
If window <> current Then
addOrgWindow = chromeDriver.SwitchTo.Window(window)
End If
Next
'chromeDriver.ExecuteScript("document.getElementById('tsTabs_ClientState').value='{'selectedIndexes':['0'],'logEntries':[],'scrollState':{}}'")
'OR
chromeDriver.ExecuteScript("var tab=$get('tsTabs_ClientState'); tab.value ='{'selectedIndexes':['0'],'logEntries':[],'scrollState':{}}'")
addOrgWindow.FindElement(By.Id("Organization_txtName")).SendKeys("MagicKingdom")
addOrgWindow.FindElement(By.Id("Organization_cbIndustry_cb_Input")).SendKeys("REP")
addOrgWindow.FindElement(By.Id("lbAdd")).Click()
chromeDriver.Quit()
Catch e As Exception
chromeDriver.Quit()
MsgBox(e.ToString())
End Try
I keep getting an error at the chromeDriver.ExecuteScript(..... line as:
Started ChromeDriver (v2.1) on port 63559
System.InvalidOperationException: unknown error: Runtime.evaluate threw exceptio
n: SyntaxError: Unexpected identifier
(Session info: chrome=28.0.1500.72)
(Driver info: chromedriver=2.1,platform=Windows NT 6.1 SP1 x86_64)
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response erro
rResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecu
te, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptInternal(String script
, Boolean async, Object[] args)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object
[] args)
at VbSeTest.PopUpTest.Main() in C:\clearcase\Projects\CMS\VbSeTest\VbSeTest\P
opUpTest.vb:line 89
[8412:6008:0717/103910:ERROR:textfield.h(162)] NOT IMPLEMENTED
The javascript works in the Selenium IDE for running script to set the text field of another hidden client so I was hopping to do something similar here. I know it finds the element but it doesn't run the script. The other Stack answers here, here, or here have not proven to be what I need to solve this issue. Any help is greatly appreciated.
I think the error is in escaping your JSON string:
chromeDriver.ExecuteScript("var tab=$get('tsTabs_ClientState'); tab.value ='{'selectedIndexes':['0'],'logEntries':[],'scrollState':{}}'")
Instead, try:
chromeDriver.ExecuteScript("var tab=$get('tsTabs_ClientState'); tab.value =\"{'selectedIndexes':['0'],'logEntries':[],'scrollState':{}}\"")
I have been reading online for days and I am unable to find a solution for this that I can get working.
I would like a single exe file that unpacks to temporary location when you run the file which can be shared and sent to people. Ideally I would like to hide my JavaScript files.
I just need 1 file that can be sent easily.
-Fasani
i don't know of any simple way to do this
but i had a similar problem a while ago and i created a VB.Net program to do this for me
First download portable 32bit version of node here : Node.exe
if you have visual studio installed create a new project then from the solution explorer go to your projects properties and add node.exe and your .js file as Resources.
then in the formload (if you don't want your program to have a ui) or in a buttons click event place these code:
Try
Dim tmpp = System.IO.Path.GetTempPath & "NodeTmp"
If (Not System.IO.Directory.Exists(tmpp)) Then System.IO.Directory.CreateDirectory(tmpp)
If Not System.IO.File.Exists(tmpp & "\tmp_node.exe") Then _
My.Computer.FileSystem.WriteAllBytes(tmpp & "\node.exe", My.Resources.node, False)
System.IO.File.WriteAllText(tmpp & "\jsfile.js", My.Resources.jsfile)
System.IO.File.WriteAllText(tmpp & "\batfile.bat", """" & tmpp & "\tmp_node.exe"" """ & tmpp & "\jsfile.js""")
Dim p As New Process()
p.StartInfo.FileName = "cmd.exe"
p.StartInfo.Arguments = "/C """ & tmpp & "\pz.bat"""
p.StartInfo.CreateNoWindow = True
p.StartInfo.UseShellExecute = False
p.Start()
'Timer1.start()
Catch ex As Exception
MsgBox("Error")
End Try
the above code creates a folder called NodeTmp in the C:\user{name}\appdata\local\Temp and extracts node.exe (from a file resorce called "node") in that folder then extracts jsfile.js (from a file resource called "jsfile") in the same folder then creates a .bat file and runs it
to Delete .js file after it is run (it is created and deleted in less then 1sec so it is kind of hidden from user):
create a timer called Timer1 and set its interval to something like 150ms and uncomment the line Timer1.start() from above code and put the following sub somewhere in code
Sub pz_cleanup() Handles Timer1.tick
Try
Dim tmpp = System.IO.Path.GetTempPath & "PZT"
System.IO.File.Delete(tmpp & "\pz.bat")
System.IO.File.Delete(tmpp & "\pz.js")
Timer1.stop()
Catch ex As Exception
End Try
End Sub
This is definitely not the best way to do this , but it worked for me , the only downside it had for me so far was its need for .net framework to be installed on other users computer which not all of them had it
if you want a cmd to open and show nodes output comment the line that sets CreateNoWindow to true
----- not part of answer but if you want to have a UI and put a close button there to so users don't have to end task node from taskmanager use this code:
Try
Dim pProcess() As Process = System.Diagnostics.Process.GetProcessesByName("tmp_node")
For Each p As Process In pProcess
p.Kill()
p.WaitForExit()
Next
Catch ex As Exception
MsgBox("Error")
Return True
End Try
hope this helps , you can do similar thing in other languages too if you are more comfortable with them then VB.Net
I have this error in my WebBrowser
Error: Unable to get value of the property 'length:' object is null or undefined
even though I have this code:
CType(TabControl1.SelectedTab.Controls.Item(0), WebBrowser).ScriptErrorsSuppressed = True
Why am I getting this and how do I get rid of it?
If you are creating the Webbrowser componenet dynamically, I suggest that you set ScriptErrorsSurpressed = True at that point.
Dim wb as New WebBrowser
wb.ScriptErrorsSurpressed = True
'Other declarations...
If it is not created dynamically, then I suggest that you go to the control and manually change the setting to True in the design view.
If this doesn't work, please refer to my request/comment on your original post.
EDIT 1
This is your code:
Dim Browser As New WebBrowser
TabControl1.TabPages.Add("New Page")
Browser.Name = "Web Browser"
Browser.Dock = DockStyle.Fill
TabControl1.SelectedTab.Controls.Add(Browser)
AddHandler Browser.ProgressChanged, AddressOf Loading
AddHandler Browser.DocumentCompleted, AddressOf Done
int = int + 1
CType(TabControl1.SelectedTab.Controls.Item(0), WebBrowser).GoHome()
CType(TabControl1.SelectedTab.Controls.Item(0), WebBrowser).ScriptErrorsSuppressed = True
This is how I would write it:
Dim Browser As New WebBrowser
Browser.Name = "Web Browser"
Browser.Dock = DockStyle.Fill
AddHandler Browser.ProgressChanged, AddressOf Loading
AddHandler Browser.DocumentCompleted, AddressOf Done
TabControl1.TabPages.Add("New Page")
TabControl1.SelectedTab.Controls.Add(Browser)
int = int + 1
Browser.GoHome()
Browser.ScriptErrorsSurpressed = True
I see no need for CType() at all.
Your getting the error because the javascript file (www-home-vflVATumV.js) on the http://s.ytimg.com server in the yts/bin folder has an error or has found a dynamic error with the LENGTH property of whatever object it is trying to assess.