Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

Basic Webpage Controls with JavaScript / COM - Tutorial


  • Please log in to reply
335 replies to this topic
leehong1
  • Validating
  • 403 posts
  • Last active: May 19 2019 03:12 PM
  • Joined: 24 Nov 2008
 
Why do the variable not work ?
wb := WBGet()
Random, OutputVar, 1, 100
wb.document.forms["orderbox"].elements[0].value := %OutputVar%


sinkfaze
  • Moderators
  • 6367 posts
  • Last active: Nov 30 2018 08:50 PM
  • Joined: 18 Mar 2008
No percent signs:

 
wb.document.forms["orderbox"].elements[0].value := OutputVar
 

scout
  • Members
  • 134 posts
  • Last active: Jun 11 2015 01:41 PM
  • Joined: 11 Apr 2011

Hi guys... 4 hours and i still cant get this aswer.

 

I cant figure out how to refer to this fields:

 

 

http://www.receita.f...solicitacao.asp

 

I want to fill the CNPJ Field. I also tried to click in the "Consultar" button, but wow, almost giving up.

f1::
Pwb := ComObjCreate("InternetExplorer.Application")
Pwb.Visible := True
Pwb.Navigate(ValidaCNPJ)
IELoad(Pwb)
Pwb.document.getElementsByTagName("Consulta").Click()
;Pwb.document.forms("frmConsulta").cnpj.value := "teste"
Msgbox, 48, Jeneves - Ajuda, Digite o código de verificação
return

I tried so many diferent ways...... im using Iwb2 Learner, but i think the problem is that this fields are inside of a form?!

 

Ty.

 

 



Jackie Sztuk _Blackholyman
  • Spam Officer
  • 3757 posts
  • Last active: Apr 03 2016 08:47 PM
  • Joined: 28 Feb 2012
Its not just in a form but also in a frame

so you frist need to access the frame and then the element you need

Example
url = http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp

wb := ComObjCreate("InternetExplorer.Application")
wb.Visible := true
wb.Navigate(url)
While wb.readyState != 4 || wb.document.readyState != "complete" || wb.busy ; wait for the page to load
	Sleep, 10

frames := wb.document.parentwindow.frames

frames[1].document.all.cnpj.value := "SomeValue"
msgbox
wb.quit()
Hope it helps
Helping%20you%20learn%20autohotkey.jpg?d

[AHK] Version. 1.1+ [CLOUD] DropBox ; Copy [WEBSITE] Blog ; About

scout
  • Members
  • 134 posts
  • Last active: Jun 11 2015 01:41 PM
  • Joined: 11 Apr 2011

Its not just in a form but also in a frame

so you frist need to access the frame and then the element you need

Example

url = http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp

wb := ComObjCreate("InternetExplorer.Application")
wb.Visible := true
wb.Navigate(url)
While wb.readyState != 4 || wb.document.readyState != "complete" || wb.busy ; wait for the page to load
	Sleep, 10

frames := wb.document.parentwindow.frames

frames[1].document.all.cnpj.value := "SomeValue"
msgbox
wb.quit()
Hope it helps

 

 

Wow! You are amazing!! My doubt was "is this a frame OR is this a form". Makes sense now, so every time its show up  "Frame.#"  in the IwB2, its means its inside a frame. You used the frames[1] because its Frame.1?

 

Thank you so much.



scout
  • Members
  • 134 posts
  • Last active: Jun 11 2015 01:41 PM
  • Joined: 11 Apr 2011

By the way, i would like to get a direction for my next steps of my scripts.

 

My steps are:

 

1) Open the URL

2) Fill the CNPJ field

3) Wait for the user to fill the Captcha code

4) Wait for the user click in the submit button

 

-------

 

After that a new page will be loaded (the url in the broswer is the same as the first page)

1) I want to call the function to wait the page to be full loaded - But i don't know how to check if the broswer opened the new page, since the url is the same. Any idea?

2)I will print the page in .pdf - I already set the Bullzip Pdf Printer as default printer - There is any way to send a COM command to print the current page?

 

 

Thats all, my main doubt now is about, how to know if the user clicked on the Submit button to call the IELoad Function?

 

Thank you so much.



scout
  • Members
  • 134 posts
  • Last active: Jun 11 2015 01:41 PM
  • Joined: 11 Apr 2011

Here is my code:

 

Im monitoring if the new page is loaded by the captcha code + InnerText.

 

If you want to simulate what the code do: Use 54547633000143 as a CNPJ example

 

I think my code is not using the best practice, so i would like to get some directions where i can make the code better:

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
#Warn  ; Recommended for catching common errors.
#SingleInstance force
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.


OpcaoPrint := 0 ;Utilizo para diferenciar a impressão em pdf da Receita/Sintegra

;Le o nome da impressora que sera utilizada para imprimir em pdf
FileReadLine, Impressora, %A_WorkingDir%\Infos\Infos.txt, 1
    if ErrorLevel
        MsgBox, "printer.txt" Não encontrado!

;Le o CNPJ
FileReadLine, CNPJ, %A_WorkingDir%\Infos\Cliente_Temp.txt, 1
    if ErrorLevel
        MsgBox, "CNPJ_Temp.txt" Não encontrado!

;Le o nome fantasia
FileReadLine, NomeFantasia, %A_WorkingDir%\Infos\Cliente_Temp.txt, 2
     if ErrorLevel
        MsgBox, "CNPJ_Temp.txt" Não encontrado!
 
 
IELoad(Pwb)	;Funcao que verifica se a pagina foi carregada
{
Loop
	Sleep, 50
Until	(pwb.readyState=4 && pwb.document.readyState="complete" && !pwb.busy)
}


;Pega a impressora padrão
GetDefaultPrinter() {
	global gPrinter
	nSize := VarSetCapacity(gPrinter, 256)
	DllCall("winspool.drv\GetDefaultPrinterW", "str", gPrinter, "UintP", nSize)
	Return gPrinter
	}

;Define Impressora
SetDefaultPrinter(sPrinter) {
	DllCall("winspool.drv\SetDefaultPrinterW", "str", sPrinter)
	TrayTip, Jeneves: , %sPrinter% selecionada como default., 10, 17
	}
	
;Pega Impressora Padrão para voltarmos a configuração depois
GetDefaultPrinter()
;Seta BullZip como impressora padrao
SetDefaultPrinter(Impressora)
TrayTip, Jeneves: , Validando CNPJ - Receita Federal, 10, 17
Pwb := ComObjCreate("InternetExplorer.Application")
Pwb.Visible := True
Pwb.Navigate("http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp")
IELoad(Pwb)
;Vamos digitar o CNPJ
frames := Pwb.document.parentwindow.frames
frames[1].document.all.cnpj.value := CNPJ
;Vamos monitorar o preenchimento do Captcha
Gosub, ValidaCaptchaReceita
Goto, imprime
return


ValidaCaptchaReceita:
tamanho := frames[1].document.all.captcha.value
;Vamos verificar o preenchimento do Captcha, quando atingir 6 digitos tomamos as ações abaixo
While StrLen(tamanho) < 6 {
	tamanho := frames[1].document.all.captcha.value
	sleep, 10
}
;chegamos a 6 digitos, vamos clickar no botão de Consulta
frames[1].document.all.submit1.Click()
IELoad(Pwb)
;Capturamos o inner text e verificamos se houve erro ou nao no captcha
text := frames[1].document.documentElement.innerText
IfInString, text, Esclarecimentos
{
	;O código digitado é incorreto, vamos aguardar o novo preenchimento
	Gosub, ValidaCaptchaReceita
	return
}
	else
	return
	
ValidaCaptchaSintegra:
tamanho := Pwb.document.all.key.value
;Vamos verificar o preenchimento do Captcha, quando atingir 4 digitos tomamos as ações abaixo
While StrLen(tamanho) < 4 {
	tamanho := Pwb.document.all.key.value
	sleep, 10
}
;chegamos a 4 digitos, vamos clickar no botão de Consulta
Send, {Enter}
IELoad(Pwb)
;Capturamos o inner text e verificamos se houve erro ou nao no captcha
text := Pwb.document.documentElement.innerText
IfInString, text, incorreto
{
	;O código digitado é incorreto, vamos aguardar o novo preenchimento -
	Pwb.Navigate("http://pfeserv1.fazenda.sp.gov.br/sintegrapfe/consultaSintegraServlet")
	IELoad(Pwb)
	Pwb.document.all.cnpj.value := CNPJ
	Gosub, ValidaCaptchaSintegra
	return
}
	else
	return

Imprime:
if (OpcaoPrint = 0) 
	{
	TrayTip, Jeneves: , Iniciando Impressão - Receita Federal, 10, 17
	Pwb.document.parentWindow.print
	WinWaitActive, Print
	send, {ENTER}
	WinWaitActive, Bullzip
	send, ^a
	sleep, 200
	AquivoValidaCNPJ = %A_WorkingDir%\Receita Federal - %CNPJ%.pdf
	Send,%AquivoValidaCNPJ%
	loop 2 {
	send, {TAB}
	sleep, 200
	}
	Send, {SPACE}
	sleep, 200
	loop 2 {
	Send, {ENTER}
	sleep, 200
	}
	OpcaoPrint = 1
	Goto, Sintegra
	return
	}
	else 
	{
	TrayTip, Jeneves: , Iniciando Impressão - Sintegra, 10, 17
	Pwb.document.parentWindow.print
	WinWaitActive, Print
	send, {ENTER}
	WinWaitActive, Bullzip
	send, ^a
	sleep, 200
	AquivoValidaSintegra = %A_WorkingDir%\Sintegra - %NomeFantasia% - %CNPJ%.pdf
	Send, %AquivoValidaSintegra%
	loop 2 {
	send, {TAB}
	sleep, 200
	}
	Send, {SPACE}
	sleep, 200
	loop 2 {
	Send, {ENTER}
	sleep, 200
	}
	Pwb.quit
	OpcaoPrint = 0
	SetDefaultPrinter(gPrinter)
	Msgbox, 48, Jeneves - Ajuda,  Todos Arquivos foram gerados! Para Enviar o e-mail, clique no botão "Enviar E-mail" na Ficha
	exitapp
	}

Sintegra:
TrayTip, Jeneves: , Validando CNPJ - Sintegra, 10, 17
;Vamos abrir o site da Sintegra e Preencher o CNPJ
Pwb.Navigate("http://pfeserv1.fazenda.sp.gov.br/sintegrapfe/consultaSintegraServlet")
IELoad(Pwb)
Pwb.document.all.cnpj.value := CNPJ
Gosub, ValidaCaptchaSintegra
Goto, imprime
return

^f8::reload
^f9::exitapp 

Also, i couldn't refer to the button: Consulta CNPJ - http://pfeserv1.faze...SintegraServlet . I don't think its inside a frame or form, but if i use pwb.document.botao.Click() , its says "Click is unknown".

 

 

Any other improves are welcome happy.png



jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

... so every time its show up  "Frame.#"  in the IwB2, its means its inside a frame. You used the frames[1] because its Frame.1?


Yes - it means it's inside a frame, but NO - Frame.1 in IwB2 is not related to the frames[1] call at all. The Frame.# refers to levels of frames - that is - a frame inside a frame. You can think of it as a box inside a box inside a box. You'd actually have to open 3 boxes to get to the inner package. So, if you had Frame.1-Frame.3, you have to do something like:
document := wb.document.parentWindow.frames[id/name/index].frames[id/name/index].frames[id/name/index].document
Now, for frames[1], the 1 is the index of the frames collection. So, in this instance, the frame you wanted was the second one (zero-based) in that frames collection.

As far as getting help on your script, you'd be better off in the Support forum. This thread is a Tutorial & is designed to help with questions specifically related to the tutorial. Let me know if you'd like your posts split off & moved to the Support forum.

Jackie Sztuk _Blackholyman
  • Spam Officer
  • 3757 posts
  • Last active: Apr 03 2016 08:47 PM
  • Joined: 28 Feb 2012

Here is my code:
 
Im monitoring if the new page is loaded by the captcha code + InnerText.
 
If you want to simulate what the code do: Use 54547633000143 as a CNPJ example
 
I think my code is not using the best practice, so i would like to get some directions where i can make the code better:


you can try and wait for the page to be busy with a load
 
#Persistent
 
url = http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp
 
wb := ComObjCreate("InternetExplorer.Application")
wb.Visible := true
wb.Navigate(url)
While wb.readyState != 4 || wb.document.readyState != "complete" || wb.busy ; wait for the page to load
Sleep, 10
 
;~ Main_frame := ComObj(9,ComObjQuery(wb.document.all.main.contentWindow,"{332C4427-26CB-11D0-B483-00C04FD90119}","{332C4427-26CB-11D0-B483-00C04FD90119}"),1)
;~ msgbox % Main_frame.document.documentElement.innertext
; PPiframe.navigate("http://www.autohotkey.com")
 
frames := wb.document.parentwindow.frames
 
frames[1].document.all.cnpj.value := "54547633000143"
 
; Wait for user to enter Captcha
while, ! wb.busy ; wait for the page to start loading
    sleep 10
 
ToolTip Page now loading!
While wb.readyState != 4 || wb.document.readyState != "complete" || wb.busy ; wait for the page to load
Sleep, 10
msgbox And now its done loading!
wb.quit()
ExitApp
Hope it helps

Edit: jethrow sorry did not see your post and ofc you are right this belongs in support
Helping%20you%20learn%20autohotkey.jpg?d

[AHK] Version. 1.1+ [CLOUD] DropBox ; Copy [WEBSITE] Blog ; About

scout
  • Members
  • 134 posts
  • Last active: Jun 11 2015 01:41 PM
  • Joined: 11 Apr 2011

Good idea. Ok, i will keep my doubts in the support forum. Thank you all.



errogaht
  • Members
  • 6 posts
  • Last active: Jan 15 2014 07:07 AM
  • Joined: 02 Oct 2013
Hi!
How to delete InternetExplorer.Application cookies? from AHK?
 
 
There is basic:
 
wb := ComObjCreate("InternetExplorer.Application")
wb.Visible := True
wb.Navigate("facebook.com")
And, if im already logged in ?
 
im need to clear cookies.

im try this variants:
 
1. delete all files in temporyInternetFiles and Cookies folders - NOTHING, folders are both empty, IE restarted- but cookies is used
2. RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 4351 - NOTHIG , Cookies are unDead!
3. 
wb.Document.cookies := "" - NOTHING , cookies work
4. DllCall("Wininet.dll\InternetClearAllPerSiteCookieDecisions") - nothing, i dont known what it is...
 
MSDN is totally viewed, in 2 hours - there is no basic InternetExplorer.Application .Visible reference, there is TONS of something, but not any about InternetExplorer.Application

 
 
Please help!!!!
 
How to open an InternetExplorer.Application window, and then clear all cookies???

errogaht
  • Members
  • 6 posts
  • Last active: Jan 15 2014 07:07 AM
  • Joined: 02 Oct 2013

1. Problem

Error 0x800704a6when i try to:

ie := ComObjCreate("InternetExplorer.Application") 

2. How to FIX

 

 

This was a problem for me and rebooting the machine fixed it. –  Nick Josevski Jan 10 '12 at 2:13

 

 

However strange it may sound, a reboot did fix the problem. My mistake for assuming she had already tried that before calling me :) I am guessing an IE update got installed and the PC was waiting for a reboot... she recently got a new PC which might explain why the problem keeps coming back since our automatic update policy is to download updates when available, but to install/reboot on weekends only.

 

 

8 of my users were facing the same problem, but every time they used to getting a diff line no and a diff error code. After trying all the above steps I finally installed IE8 and reset the Roaming And Local Profile and luckily next day when i followed the issue. It was resolved

 

Original from: http://serverfault.c...-error-800704a6



jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

http://www.youtube.c...h?v=PtXtIivRRKQ



Exaskryz
  • Members
  • 3249 posts
  • Last active: Nov 20 2015 05:30 AM
  • Joined: 23 Aug 2012
!7::
wbt := ComObjCreate("InternetExplorer.Application") ; wbt is my arbitrary handle for twitch chat
wbt.Visible := True
WinWait, ahk_class IEFrame
URL = http://www.twitch.tv/chat/embed?channel=TwitchPlaysPokemon&popout_chat=true
wbt.Navigate(URL)
IELoad(wbt)
SetTimer, sendanarchy, 33000
Return

sendanarchy:
wbt.document.all.query.value := "anarchy"
Sleep 1000
wbt.document.submit.click()
Return



IELoad(wbt)    ;You need to send the IE handle to the function unless you define it as global.
{
    If !wbt    ;If wbt is not a valid pointer then quit
        Return False
    Loop    ;Otherwise sleep for .1 seconds untill the page starts loading
        Sleep,100
    Until (wbt.busy)
    Loop    ;Once it starts loading wait until completes
        Sleep,100
    Until (!wbt.busy)
    Loop    ;optional check to wait for the page to completely load
        Sleep,100
    Until (wbt.Document.Readystate = "Complete")
Return True
}

The original post was very not helpful with what to do with identifying what lines to use for a control. I'm having difficulty figuring out how to fill the textbox with anything. AHK pops up with an error:

 

 


---------------------------
Anarchy Test.ahk
---------------------------
Error:  0x80020006 - Unknown name.


Specifically: query

    Line#
    003: wbt.Visible := True  
    004: WinWait,ahk_class IEFrame
    005: URL = http://www.twitch.tv...opout_chat=true
    006: wbt.Navigate(URL)  
    007: IELoad(wbt)  
    008: SetTimer,sendanarchy,33000
    009: Return
--->    012: wbt.document.all.query.value := "anarchy"  
    013: Sleep,1000
    014: wb.document.submit.click()  
    015: Return
    020: {
    021: if !wbt  
    022: Return,False
    023: Loop

Continue running the script?
---------------------------
Yes   No   
---------------------------
 

 

 


---------------------------
Anarchy Test.ahk
---------------------------
Error:  0x80020006 - Unknown name.


Specifically: submit

    Line#
    005: URL = http://www.twitch.tv...opout_chat=true
    006: wbt.Navigate(URL)  
    007: IELoad(wbt)  
    008: SetTimer,sendanarchy,33000
    009: Return
    012: wbt.document.all.query.value := "anarchy"  
    013: Sleep,1000
--->    014: wbt.document.submit.click()  
    015: Return
    020: {
    021: if !wbt  
    022: Return,False
    023: Loop
    024: Sleep,100
    025: Until,(wbt.busy)

Continue running the script?
---------------------------
Yes   No   
---------------------------
 

 

Here's the HTML obtained with iWB2 Learner. For the Input field:

<input id="chat_text_input" class="text require_logged_in" tabIndex="1" name="chat_text_input" placeholder="Chat about this video" autocomplete="off">

 

And for the button I want to press: <span>Chat</span>

 

This seems so simple, but because of how incomplete the original post feels (yes, you gave examples of how to use seemingly random web elements, except with no instructions at all for using them or even deriving your own), I just can't figure out where to go from here.

 

Edit: I've resolved the first error. But I cannot resolve this second error.

 

javascript: document.all.chat_speak.click() is working javascript code. But I can't get it translated to COM. I tried wbt.document.chat_speak.click(), but it brings the same error message.

 

(I resolved my first error by changing wbt.document.all.query.value := "anarchy"  into wbt.document.all.chat_text_input.value := "anarchy")

 

Edit 2: I suppose I have that second error resolved now too. I needed to make it wbt.document.all.chat_speak.click()



jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

... because of how incomplete the original post feels (yes, you gave examples of how to use seemingly random web elements, except with no instructions at all for using them or even deriving your own), ...

It's worth noting that the tutorial was never meant to be an all-encompassing tutorial/reference for html/javascript/com. My teaching style has always been to give people enough information & guidance that they can get started & figure things out on their own. Temporary frustration & set-back is good - it means the user is thinking & learning for themselves. Learning how to learn beats being spoon fed any day.

Edit: I noticed you partially solved your problem. Good work.

Edit2: Looks like you tried, failed, adjusted & learned how to do this stuff. I congratulate you on thinking & learning for yourself.