Jump to content
Sign in to follow this  
Chimp

Autoit <-> Javascript roundtrip

Recommended Posts

15 hours ago, Chimp said:

or there is a way to directly attach to objects created within it?

If i get what i think you mean, then no.

14 hours ago, Chimp said:

... that listing for example could be the 'basic' gui, then, in short, I would 'write' for example this page (a timeline from this site) into the embbedded IE, and finally use "ScriptControl" to interact with the timeline so to use it as a graphic frontend where to display data, while data is managed by AutoIt on an SQLite database for example...
I was trying now to do something like that, but I'm having problems on opening the above page into the embedded IE (the timeline is not shown...)
I will come back to this tomorrow.... 02:58 AM here....

.....thanks for any help.... :)

Well the IE object should have almost the same functions as ScriptControl.

I'll try to look into your idea and post an example with an edit if I'm successful.

 

Edit:

So I've looked into it, and it's more annoying that rewarding, but it's possible. I tried the vis library they use on your example site, and google charts, but both does not play well with the outdated functionality. you could try looking into js librarys that works with IE8, or make a basic one yourself :)

I'll look into some better code tomorrow when i wake up, right now i only got div's with css styling ;)

 

Edit2:

So I've made a static example with CSS from the vis timeline example you provided.

The elements are generated and set with AutoIt, but it might be better with pre-defined JS functions :)

Opt("GuiOnEventMode", 1)

$oIE = ObjCreate("Shell.Explorer.2")
$hGui = GUICreate("Title", 700, 320)
GUISetOnEvent(-3, "_MyExit", $hGui)
GUISetState()
$hIE = GUICtrlCreateObj($oIE, 10, 10, 680, 300)
$oIE.navigate('about:blank')
$oIE.document.Write('<!DOCTYPE HTML><html><head></head><body></body></html>')

$oStyle = $oIE.document.createElement("style")
$oStyle.setAttribute('type', 'text/css')
$oStyle.styleSheet.cssText = ".timeline{border:1px solid #e5e5e5;height:183px;overflow:hidden;position:relative;}.timelinegrid-vertical{color:#4d4d4d;border-left:1px solid #e5e5e5;width:54px;height:183px;position:absolute;text-align:center;}.timelinegrid-horisontal{border-top:1px solid #e5e5e5;width:100%;height:39px;position:absolute;}.timegrid-item{position:absolute;height:34px;border:1px solid #97b0f8;background-color:#d5ddf6;box-sizing:border-box;}"
Execute('$oIE.document.getElementsByTagName("head")(0).appendChild($oStyle)')

$oDiv = $oIE.document.createElement("div")
$oDiv.className = "timeline"
$oIE.document.body.appendChild($oDiv)

For $i=1 To Floor($oDiv.offsetWidth/53)
    $oDiv2 = $oIE.document.createElement("div")
    $oDiv2.className = "timelinegrid-vertical"
    $oDiv2.style.left=($i)*55&"px"
    $oDiv2.innerHTML = StringFormat("%02i", $i)&":00"
    $oDiv.appendChild($oDiv2)
Next

For $i=1 To Floor($oDiv.offsetHeight/39)
    $oDiv2 = $oIE.document.createElement("div")
    $oDiv2.className = "timelinegrid-horisontal"
    $oDiv2.style.top=($i*39)&"px"
    $oDiv2.innerHTML = "Truck "&$i
    $oDiv.appendChild($oDiv2)
Next

$oDiv2 = $oIE.document.createElement("div")
$oDiv2.style.position="absolute"
$oDiv2.style.top="39px"
$oDiv2.style.left="55px"
$oDiv2.style.width=$oDiv.offsetWidth-55&"px"
$oDiv2.style.height=$oDiv.offsetHeight-39&"px"
$oDiv.appendChild($oDiv2)

$oDiv3 = $oIE.document.createElement("div")
$oDiv3.className = "timegrid-item"
$oDiv3.style.left = "2px"
$oDiv3.style.top = "2px"
$oDiv3.style.width = 55*3-5&"px"
$oDiv3.innerHTML = "Order 1"
$oDiv2.appendChild($oDiv3)


$oDiv4 = $oIE.document.createElement("div")
$oDiv4.className = "timegrid-item"
$oDiv4.style.left = 2+(55*7)&"px"
$oDiv4.style.top = "2px"
$oDiv4.style.width = 55*4-5&"px"
$oDiv4.innerHTML = "Order 2"
$oDiv2.appendChild($oDiv4)


$oDiv4 = $oIE.document.createElement("div")
$oDiv4.className = "timegrid-item"
$oDiv4.style.left = "2px"
$oDiv4.style.top = 2+39&"px"
$oDiv4.style.width = 55*5-5&"px"
$oDiv4.innerHTML = "Order 251"
$oDiv2.appendChild($oDiv4)


$oDiv4 = $oIE.document.createElement("div")
$oDiv4.className = "timegrid-item"
$oDiv4.style.left = 2+(55*5)&"px"
$oDiv4.style.top = 2+39&"px"
$oDiv4.style.width = 55*4-5&"px"
$oDiv4.innerHTML = "Order 252"
$oDiv2.appendChild($oDiv4)


$oDiv4 = $oIE.document.createElement("div")
$oDiv4.className = "timegrid-item"
$oDiv4.style.left = 2+(55*9)&"px"
$oDiv4.style.top = 2+39&"px"
$oDiv4.style.width = 55*3-5&"px"
$oDiv4.innerHTML = "Order 253"
$oDiv2.appendChild($oDiv4)


$oDiv4 = $oIE.document.createElement("div")
$oDiv4.className = "timegrid-item"
$oDiv4.style.left = 2+(55*0)&"px"
$oDiv4.style.top = 2+39*2&"px"
$oDiv4.style.width = 55*4-5&"px"
$oDiv4.innerHTML = "Order 501"
$oDiv2.appendChild($oDiv4)


$oDiv4 = $oIE.document.createElement("div")
$oDiv4.className = "timegrid-item"
$oDiv4.style.left = 2+(55*4)&"px"
$oDiv4.style.top = 2+39*2&"px"
$oDiv4.style.width = 55*4-5&"px"
$oDiv4.innerHTML = "Order 502"
$oDiv2.appendChild($oDiv4)

While 1
    Sleep(10)
WEnd

Func _MyExit()
    Exit
EndFunc

 

Edited by genius257

Share this post


Link to post
Share on other sites

Hi @genius257, thanks for your listing,
I see that you built a 'timeline' using interesting methods, but in this way we get a static Timeline. I have to 'rebuild' the whole timeline by 'hard coding' for any variation on the content or for any moving of the view. We loose the advantage of using the many ready made javascript libraries.

In this way we are loosing a bit the initial goal of this topic, that is: Using an embedded Browser control with html elements and javascript libraries within and be able to interact and manage all that stuff from AutoIt.
For a better explanation of my goal as from post#20, I post here a simple 'runnable' snippet. It performs what I was in search of, by using  "Shell.Explorer.2" and not "ScriptControl". As you can see the Timeline can be slided directly on the embedded browser or you can also use the 2 buttons from autoit to control the Timeline. This is just a very simple interaction, but is the proof of concept.

To use the script you have to save the script and the Timeline code in the same path.

Here the script:

$oIE = ObjCreate("Shell.Explorer.2")
Local $sHTML = ""
$sHTML &= '<!DOCTYPE HTML><html>' & @CRLF
$sHTML &= '<head>' & @CRLF
$sHTML &= '<meta http-equiv="X-UA-Compatible" content="IE=edge" />' & @CRLF ; IE=edge
$sHTML &= '<script>var JSglobal = (1,eval)("this");</script>' & @CRLF
$sHTML &= '<script src="https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.min.js"></script>' & @CRLF
$sHTML &= '<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.min.css" rel="stylesheet" type="text/css" />' & @CRLF
$sHTML &= '</head>' & @CRLF
$sHTML &= '<body>' & @CRLF
$sHTML &= FileRead('SimpleTimelineBody.txt')
$sHTML &= '</body></html>' & @CRLF

Local $sPage = @ScriptDir & '\Page.html'
Local $hFile = FileOpen($sPage, 2) ;  $FO_OVERWRITE (2) = Write mode (erase previous contents)
FileWrite($hFile, $sHTML)
FileFlush($hFile)
FileClose($hFile)

$hGui = GUICreate("Timeline", 800, 450)
Local $hRight = GUICtrlCreateButton(' Go right --->', 650, 380, 100, 50)
Local $hLeft = GUICtrlCreateButton(' <---  Go left', 50, 380, 100, 50)
GUISetState(@SW_SHOW)
$hIE = GUICtrlCreateObj($oIE, 10, 10, 780, 350)
$oIE.navigate('file:///' & $sPage)

; this waits till the document is ready to be used (portion of code from the _IELoadWait() function in IE.au3)
While Not (String($oIE.readyState) = "complete" Or $oIE.readyState = 4)
    Sleep(100)
WEnd
While Not (String($oIE.document.readyState) = "complete" Or $oIE.document.readyState = 4)
    Sleep(100)
WEnd

; https://msdn.microsoft.com/en-us/library/52f50e9t(v=vs.94).aspx
Local $ohJS = $oIE.document.parentwindow.JSglobal ; $ohJS is a reference to the javascript Global Obj
; ---- now the javascript engine can be used in our AutoIt script using the $ohJS reference ----

; Loop until the user exits.
While 1
    Switch GUIGetMsg()
        Case -3 ; $GUI_EVENT_CLOSE
            ExitLoop

        Case $hRight
            ; Interact with javascript - move right
            $ohJS.move(0.2) ; eval('move( 0.2);')

        Case $hLeft
            ; Interact with javascript - move left
            $ohJS.move(-0.2) ; eval('move( 0.2);')
    EndSwitch
WEnd
GUIDelete($hGui)

Here the HTML/Javascript code: save this file in the same path of the above script with this name: SimpleTimelineBody.txt 

<div id="visualization"></div>

<script>
// DOM element where the Timeline will be attached
var container = document.getElementById('visualization');

  var groups = new vis.DataSet([
    {id: 0, content: 'Mr. bean', value: 1},
    {id: 1, content: 'Jack Black', value: 3},
    {id: 2, content: 'Danny DeVito', value: 2},
    {id: 3, content: 'Stan Laurel', value: 6},
    {id: 4, content: 'Oliver Hardy', value: 5},
    {id: 5, content: 'Jim Carrey', value: 4}
  ]);

// Create a DataSet (allows two way data-binding)
var items = new vis.DataSet([
{id: 1, group: 0, content: 'item 1', start: '2013-04-20'},
{id: 2, group: 1, content: 'item 2', start: '2013-04-14'},
{id: 3, group: 2, content: 'item 3', start: '2013-04-18'},
{id: 8, group: 3, content: 'Range', start: '2013-04-16', end: '2013-04-19'},
{id: 5, group: 4, content: 'item 5', start: '2013-04-25'},
{id: 6, group: 5, content: 'item 6', start: '2013-04-27'}
]);

// Configuration for the Timeline
var options = {orientation: 'top'};

// Create a Timeline
var timeline = new vis.Timeline(container, items, options); // items,
  timeline.setGroups(groups);
  timeline.setItems(items);

    /**
     * Move the timeline a given percentage to left or right
     * @param {Number} percentage   For example 0.1 (left) or -0.1 (right)
     */
    function move (percentage) {
        var range = timeline.getWindow();
        var interval = range.end - range.start;

        timeline.setWindow({
            start: range.start.valueOf() - interval * percentage,
            end:   range.end.valueOf()   - interval * percentage
        });
    }
</script>

What I would like to know, is If and How the same result can be obtained by the "ScriptControl".

Thanks a lot again for your help and effort.

Edited by Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Share this post


Link to post
Share on other sites
5 hours ago, Chimp said:

Here the script

Looks nice :) i guess i did something wrong, when trying to apply the vis library in a example ;)

5 hours ago, Chimp said:

What I would like to know, is If and How the same result can be obtained by the "ScriptControl".

No it would not. "ScriptControl" does not have DOM integration or any visual representation.

5 hours ago, Chimp said:

Thanks a lot again for your help and effort.

No problem :) Anytime :D

Share this post


Link to post
Share on other sites
5 hours ago, Chimp said:

now the javascript engine can be used in our AutoIt script using the $ohJS reference

Very interesting.
 


Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest beginning - communication with GitHub REST API Forum Rules *
Include Dependency Tree (Tool for analyzing script relations)
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskScheduler

PDF Related:https://www.autoitscript.com/forum/topic/177368-how-to-get-reference-to-pdf-object-embeded-in-ie/ *

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2020-09-20

Share this post


Link to post
Share on other sites

.... Just for the record, (for those who can be interested)

The DOM's window object, has some methods that you can easly call from within AutoIt (https://msdn.microsoft.com/en-us/library/ms535873(v=vs.85).aspx)
One of this methods is setTimeout that allows you to execute a function or javascript code after an interval of time expressed in milliseconds.

Well this is very interesting because it also allows you to execute chunks of javascript code passed as a string (of course the interesting is that you can pass the javascript code from within AutoIt). Also, if you set the timeout to 0, the code you passed is executed immediately.

In my opinion, this method can be a perfect replacement of the execScript method  no longer supported starting with IE11.

Replacing this safer method in this snippet by @genius257 we can reference and call the eval Javascript function from within AutoIt, allowing interesting interaction between the two worlds (IE+javascript and AutoIt)

here a simple and little example just to show what I'm talking about.

#include <ie.au3>

Local $oIE = _IECreate()
Local $oDocument = _IEDocGetObj($oIE)
Local $oWindow = $oDocument.ParentWindow

; I'm not been able (for now) to directly refeence the Javascript Global Object from within AutoIt
; anyway it can be referenced via the following JSglobal javascript variable accessed from AutoIt via the eval method
$oWindow.setTimeout("JSglobal = (1,eval)('this');", 0) ; a reference to the JavaScript Global Object

; the following JSeval variable will be referenced directly from AutoIt (see below)
$oWindow.setTimeout("document.body.JSeval = eval;", 0) ; a reference to the eval method

Sleep(2000) ; give a little time to the browser to create above variables within the javascript environment.

$eval = $oIE.Document.body.JSeval ; a reference to the eval javascript method from within AutoIt
MsgBox(0, "Debug", "The $eval variable is of type " & VarGetType($eval) & @CRLF & "and is a refernce to the eval javascript method")

; Using the Javascript Global Object via eval
; https://docs.microsoft.com/en-us/scripting/javascript/reference/global-object-javascript
MsgBox(0, "Debug", "Script infos:" & @CRLF & _
        "-------------" & @CRLF & _
        "Script Engine:  " & $eval('JSglobal.ScriptEngine()') & @CRLF & _
        "Script Version: " & $eval('JSglobal.ScriptEngineBuildVersion()'))

; calling javascript methods
; we use a javascript method to format a number
; and we get the result from javascript directly in an AutoIt variable by the javascript eval method
$i = 1000000 ; an unformatted number
Local $result = $eval('parseInt( ' & $i & ' ).toLocaleString();')
MsgBox(0, "Debug", "This is a number formatted by javascript: " & $result)

$eval("alert('Bye from JavaScript... see you later\nClick OK to quit')")

_IEQuit($oIE)

 

Edited by Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Share this post


Link to post
Share on other sites
8 hours ago, junkew said:

Maybe this is also interesting for microsoft edge javascript if you just need javascript unrelated to an html dom

Hi @junkew,  as you sayd, using Chakra is a nice and handy way to have javascript at your fingertips if you don't need to interact with a DOM.

The goal here  is instead to be able to interact and take control of a "full–fledged" IE object, including all underlying related DOM objects,  loaded javascript libraries, canvas..... and so on.

This was already feasible using the "Browser Control" (Shell.Explorer.2) (see earlyer posts above) but with the limitations that the shell.Explorer2 object is not used by InternetExplorer.  It uses insteadand the "InternetExplorer.Application" object for the rendering of the web pages. So you were not able to "take the control and interact" with a web page loaded in the Internet Explorer browser. With the above way from post #25, is instead also possible to "attach" an "InternetExplorer.Application" that is an $oIE object created using the _IECreate() function for example.

 

6 hours ago, Danp2 said:

@Chimp Is the JSglobal portion really necessary? From my brief testing, JSglobal appears to be the same as the window object.

Hi @Danp2 perhaps you are right, there is no need to reference also the Javscript Global Object because Global members can also be accessed just using eval, thanks for your feedback.
Here a modified script working wthout the direct use of the Global Object.
I've includaed also a little test on using some methods of the global object (escape, unescape) and the JSON.stringify method to pass an javascript array to AutoIt in a form of JSON string.
Also you can uncomment the 2 #include and 2 lines in the script to see how to recreate an Javascript array in an AutoIt array using @Ward's JSON udf.

#include <ie.au3>
; #include <array.au3>
; #include 'Json.au3' ; <-- get it here https://www.autoitscript.com/forum/topic/148114-a-non-strict-json-udf-jsmn/?do=findComment&comment=1286205

Local $oIE = _IECreate()
Local $oDocument = _IEDocGetObj($oIE)
Local $oWindow = $oDocument.ParentWindow

; I'm not been able (for now) to directly refeence the Javascript Global Object from within AutoIt
; anyway, as pointed by @danp2, there is no need to have this reference because Global members can be accessed just using eval.
; If is ever needed, it can be referenced setting the following JSglobal javascript variable and accessed from AutoIt via the eval method
; $oWindow.setTimeout("JSglobal = (1,eval)('self');", 0) ; a reference to the JavaScript Global Object

; the following JSeval variable will be referenced directly from AutoIt (see below)
$oWindow.setTimeout("document.body.JSeval = eval; ", 0) ; a reference to the eval method

$oWindow.setTimeout('MyGlobalVar = "Hello!!";', 0) ; a variable without the 'var' prefix is declared in the global scope
$oWindow.setTimeout('alert(MyVar);', 0) ; get a variable from the global scope

Sleep(2000) ; give a little time to the browser to create above variables within the javascript environment.

$JSeval = $oIE.Document.body.JSeval ; a reference to the eval javascript method from within AutoIt

MsgBox(0, "Debug", "The $JSeval variable is of type " & VarGetType($JSeval) & @CRLF & "and is a refernce to the eval javascript method")

MsgBox(0, "Debug ScriptEngine", "Script infos:" & @CRLF & _
        "-------------" & @CRLF & _
        "Script Engine:  " & $JSeval('ScriptEngine()') & @CRLF & _
        "Script Version: " & $JSeval('ScriptEngineBuildVersion()'))

Local $sString = "1 2 3 a b c"
MsgBox(0, "Debug escape/unescape", $JSeval('escape("' & $sString & '")') & @CRLF & $JSeval('unescape("' & $JSeval('escape("' & $sString & '")') & '")'))

; calling javascript methods
; we use a javascript method to format a number
; and we get the result from javascript directly in an AutoIt variable by the javascript eval method
$i = 1000000 ; an unformatted number
Local $result = $JSeval('parseInt( ' & $i & ' ).toLocaleString();')
MsgBox(0, "Debug", "This is a number formatted by javascript: " & $result)

; Stringify an arrat
$oWindow.setTimeout('MyJsArray = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];', 0) ; an array in the global scope
Sleep(2000)
$sJson = $JSeval('JSON.stringify(MyJsArray);') ; pass the array in form of JSON string
MsgBox(0, "Debug  Json Array", $sJson)

; ReCreate the array in Javascript:
; uncomment following 2 lines to crate an AutoIt array from the Json string
; Local $aArray = Json_Decode($sJson)
; _ArrayDisplay($aArray)

$JSeval("alert('Bye from JavaScript... see you later\nClick OK to quit')")
_IEQuit($oIE)

 

Edited by Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By mdwerne
      Hello,
      Before Broadcom took over Symantec, I was able to use the following code as the base to scrape daily definition downloads from the web. Since the pages were moved over to the Broadcom web servers, I get a page full of what I believe may be JavaScript instead of the fully rendered page that lies behind it. Does anyone have any suggestions as to how I can read the full rendered webpage using AutoIt?
      #include <IE.au3> $oIE_DEFS = _IECreate("https://www.broadcom.com/support/security-center/definitions/download/detail?gid=sep14", 0, 0, 1, 1) $sString_DEFS = _IEBodyReadHTML($oIE_DEFS) MsgBox(0, "https://www.broadcom.com/support/security-center/definitions/download/detail?gid=sep14", $sString_DEFS) The above code will show the JavaScript, but if you go to the URL in a browser that has JavaScript enabled, you will see the fully rendered page that I would like to access. I hope my question makes sense, and I would appreciate any suggestions to get this working again.
      All the best,
      -Mike
    • By Chimp
      Making the integration between AutoIt and the BrowserControl easier may facilitate the development of interesting programs. Just think of all those (fantastic) libraries and frameworks available for javascript that could be integrated and exploited in an AutoIt program. For example, to graphically present the results of an AutoIt processing in the GUI, ... and many other possibilities. Providing the basic functions to implement this synergistic interaction is the purpose of this post (if for no other reason, just even to collect some tests done over time here and there, so as not to leave them scattered and easily find them in just one place)
      In this UDF there are only a few functions (or better if called wrappers), but I hope to add more as I go and, even better, to receive suggestions and advice on new features and techniques to improve and expand it.
      _WebBrowser_GUICtrlCreate Create an Internet Explorer 'Browser Control' _WebBrowser_SetHTML Set a new HTML listing in the BrowserControl _WebBrowser_CSS_Inject Creates into the html document a CSS node element with embedded the passed CSS _WebBrowser_JS_Inject Creates into the html document a javascript node element with embedded the passed javascript _WebBrowser_JS_Eval Evaluates a passed string as JavaScript code and executes it _WebBrowser_JS_setTimeout Calls a javascript function or executes a javascript code snippet [option after a specified delay] _WebBrowser_JS_ElementGetRef Retrieves a reference to an element suitable to be used from AutoIt _WebBrowser_ExecuteDotNotation Get a reference to an object's child member or the value of a property, by means of a dotted path _WebBrowser_BasicHTML Returns a basic html page listing (a little enhanced than about:blank) The three examples provided in the attached ziped file are a bit 'improvised' and do not take advantage of all the possibilities offered by the underlying javascript libraries used. They are just three "hello world" scripts to test the ABC of the interaction with the "BrowserControl".
      (ToDo: Interaction with javascript custom events)
      Bug reports, creative criticisms and suggestions (particularly regarding the interaction with javascript custom events) are welcome
      I hope you can have fun with the Browser Control
      BrowserControl.zip
    • By Chimp
      This is a little experiment that makes use of a "Browser Control" embedded in a GUI in order to be able to use AutoIt, HTML, JavaScript and CSS all together.
      This little toy will only work on systems with IE11.
      The purpose is to drag all the names of the scientists & drop on the right ones. (among scientists it has also infiltrated an intruder). I hope you find it entertaining.
      I've posted it here in the hope to have some suggestions on how to improve it all (I mean the interaction between Autoit Javascript html and css). Thanks
      ; this works on systems with IE11 ; ------------------------------- #include <GUIConstantsEx.au3> #include <array.au3> Global $oIE, $oDocument, $ohJS, $sDroping Global $iCorrect = 0, $iGoal = 11 Example() Exit Func Example() Local $aScientists[12][2] = _ [["Schrodinger", "Schrodinger"],["Planck", "Planck"],["Pauli", "Pauli"],["Einstein", "Einstein"], _ ["Chimp", "Chimp"],["Dirac", "Dirac"],["Heisenberg", "Heisenberg"],["Born", "Born"], _ ["De Broglie", "De_Broglie"],["Bohr", "Bohr"],["Sommerfeld", "Sommerfeld"],["", "empty"]] Local $oIE = ObjCreate("Shell.Explorer.2") ; Create a BrowserControl Local $hGUI = GUICreate("", 660, 600, 30, 30) GUICtrlCreateObj($oIE, 0, 0, 660, 600) ; Place BrowserControl on the GUI GUISetState() ;Show GUI $oIE.navigate('about:blank') ; file:///' & @ScriptDir & '\WhoIsWho.html') While Not String($oIE.readyState) = 'complete' ; wait for about:blank Sleep(100) WEnd ; this waits till the document is ready to be used (portion of code from IE.au3) While Not (String($oIE.readyState) = "complete" Or $oIE.readyState = 4) Sleep(100) WEnd While Not (String($oIE.document.readyState) = "complete" Or $oIE.document.readyState = 4) Sleep(100) WEnd $oIE.document.Write(_GetHTML()) ; inject lising directly to the HTML document: $oIE.document.close() ; close the write stream $oIE.document.execCommand("Refresh") While Not String($oIE.readyState) = 'complete' ; wait for readyState after a refresh Sleep(100) WEnd ; https://msdn.microsoft.com/en-us/library/52f50e9t(v=vs.94).aspx ; $ohJS is a reference to the javascript Global Obj ; ------------------------------------------------- $ohJS = $oIE.document.parentwindow.JSglobal $oDocument = $oIE.document Local $oTable1 = $ohJS.table1 Local $oTable2 = $ohJS.table2 _Randomize($aScientists, $oTable1) ; --- Setup events ------------ ; https://msdn.microsoft.com/en-us/library/hh801967(v=vs.85).aspx Local $aoEventObject[2] $aoEventObject[0] = ObjEvent($oTable1, "IEEvent_", "HTMLTableEvents2") $aoEventObject[1] = ObjEvent($oTable2, "IEEvent_", "HTMLTableEvents2") ; ----------------------------- ; Loop until the user exits. While 1 Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop EndSwitch If $iCorrect = $iGoal Then _Goal() _Randomize($aScientists, $oTable1) $iCorrect = 0 EndIf WEnd ; the end For $i = 0 To UBound($aoEventObject) - 1 $aoEventObject[$i] .stop Next $aoEventObject = 0 ; Kill the Event Object $oIE = 0 ; Remove IE from memory (not really necessary). GUIDelete($hGUI) ; Remove GUI EndFunc ;==>Example ; --- event management zone --- ; following functions are fired by events occurred in the browser control Volatile Func IEEvent_onDragstart($oEvent) ; we save the ID of the dragged obj into the $sDroping variable ; for a later use in the drop function $sDroping = $oEvent.srcElement.ID EndFunc ;==>IEEvent_onDragstart Volatile Func IEEvent_onDragOver($oEvent) $ohJS.event.preventDefault() EndFunc ;==>IEEvent_onDragOver Volatile Func IEEvent_onDrop($oEvent) $ohJS.event.preventDefault() If $sDroping <> "" Then If $oDocument.getElementById($sDroping).innerText <> $oEvent.srcElement.innerText Then If $oEvent.srcElement.ClassName = $oDocument.getElementById($sDroping).ClassName Then $oEvent.srcElement.innerText = $oDocument.getElementById($sDroping).innerText $oDocument.getElementById($sDroping).innerText = "" $oDocument.getElementById($sDroping).draggable = False $oDocument.getElementById($sDroping).setAttribute("style") = "background-color: #80ff80;" $iCorrect += 1 Else For $i = 1 To 3 $oDocument.getElementById($sDroping).setAttribute("style") = "background-color: #ff0000;" Sleep(125) $oDocument.getElementById($sDroping).setAttribute("style") = "background-color: #ffffff;" Sleep(125) Next EndIf EndIf $sDroping = "" EndIf EndFunc ;==>IEEvent_onDrop Func _Randomize(ByRef $aScientists, ByRef $oTable) Local $iRows = ($oTable.rows.length) - 1 Local $iCols = ($oTable.rows.item(0).cells.length) - 1 Local $index _ArrayShuffle($aScientists) For $y = 0 To $iRows For $x = 0 To $iCols $index = ($y * ($iCols + 1)) + $x $oTable.rows.item($y).cells.item($x).innerText = $aScientists[$index][0] ; text $oTable.rows.item($y).cells.item($x).className = $aScientists[$index][1] ; class $oTable.rows.item($y).cells.item($x).draggable = $aScientists[$index][0] <> "" Next Next EndFunc ;==>_Randomize Func _Goal() Local $oTable1 = $ohJS.table1 ; names Local $oTable2 = $ohJS.table2 ; photos Local $iRows = ($oTable1.rows.length) Sleep(250) Local $iCols = 6 ; ($oTable1.rows.item(0).cells.length) Local $aIndex[$iRows * $iCols], $sTemp For $i = 0 To UBound($aIndex) - 1 $aIndex[$i] = $i ; + 1 Next _ArrayShuffle($aIndex) For $i = 0 To UBound($aIndex) - 1 $oTable2.rows.item(Int($aIndex[$i] / $iCols)).cells.item(Mod($aIndex[$i], $iCols)).innerText = "" $oTemp0 = $oTable2.rows $oTemp1 = $oTemp0.item(Int($aIndex[$i] / $iCols)).cells $oTemp2 = $oTemp1.item(Mod($aIndex[$i], $iCols)).getAttribute("style") $oTable2.rows.item(Int($aIndex[$i] / $iCols)).cells.item(Mod($aIndex[$i], $iCols)).setAttribute("style") = "background-color: " & _rndColor() Sleep(100); MsgBox(0,"Debug",$sTemp) $oTable2.rows.item(Int($aIndex[$i] / $iCols)).cells.item(Mod($aIndex[$i], $iCols)).setAttribute("style") = $oTemp2 Next For $x = 1 To 2 For $i = 0 To UBound($aIndex) - 1 $oTable1.rows.item(Int($aIndex[$i] / $iCols)).cells.item(Mod($aIndex[$i], $iCols)).setAttribute("style") = "background-color: " & _rndColor() Sleep(100) $oTable1.rows.item(Int($aIndex[$i] / $iCols)).cells.item(Mod($aIndex[$i], $iCols)).setAttribute("style") = "background-color: #ffffff;" Next Next EndFunc ;==>_Goal Func _rndColor() Return String("#" & Hex(Random(0, 255, 1), 2) & Hex(Random(0, 255, 1), 2) & Hex(Random(0, 255, 1), 2) & ";") EndFunc ;==>_rndColor Func _GetHTML() Local $sHTML = _ "<!DOCTYPE HTML>" & @CRLF & _ "<html>" & @CRLF & _ "<head>" & @CRLF & _ "<meta http-equiv=""X-UA-Compatible"" content=""IE=edge"" />" & @CRLF & _ " <script type=""text/javascript"">" & @CRLF & _ " var JSglobal = (1,eval)(""this"");" & @CRLF & _ " </script>" & @CRLF & _ "</head>" & @CRLF & _ "<body>" & @CRLF & _ "<h2>Who is who?</h2>" & @CRLF & _ "<p>Drag&Drop names on the right scientist</p>" & @CRLF & _ "<img src=""https://i.imgur.com/STWql7w.jpg""" & @CRLF & _ "height=""394"" width=""640""" & @CRLF & _ "style=""position: absolute; left: 10px; top: 100px;"">" & @CRLF & _ "" & @CRLF & _ "<style>" & @CRLF & _ ".target td {width: 100px; height: 160px; text-align: center; color: white; font-weight: bold; vertical-align: bottom; border: 0px solid grey;}" & @CRLF & _ ".source td {width: 100px; height: 30px; text-align: center; border: 1px solid red;}" & @CRLF & _ "</style>" & @CRLF & _ "" & @CRLF & _ "<table class=""target"" style=""position: absolute; left: 25px; top: 100px;"" id=""table2"">" & @CRLF & _ " <tr><td class=""Schrodinger""></td><td class=""Planck""></td><td class=""Pauli""></td><td class=""Einstein""></td><td class=""Chimp""></td><td class=""Dirac""></td></tr>" & @CRLF & _ " <tr><td class=""Heisenberg""></td><td class=""Born""></td><td class=""De_Broglie""></td><td class=""Bohr""></td><td class=""Sommerfeld""></td><td class=""empty""></td></tr>" & @CRLF & _ "</table>" & @CRLF & _ "" & @CRLF & _ "<table class=""source"" style=""position: absolute; left: 10px; top: 504px;"" id=""table1"">" & @CRLF & _ " <tr><td ID=""td1""></td><td ID=""td2""></td><td ID=""td3""></td><td ID=""td4"" ></td><td ID=""td5"" ></td><td ID=""td6"" ></td></tr>" & @CRLF & _ " <tr><td ID=""td7""></td><td ID=""td8""></td><td ID=""td9""></td><td ID=""td10""></td><td ID=""td11""></td><td ID=""td12""></td></tr>" & @CRLF & _ "</table>" & @CRLF & _ "</body>" & @CRLF & _ "</html>" Return $sHTML EndFunc ;==>_GetHTML  
    • By Phil1991
      Hi,
      I'm working on an interface and I have a problem with zoom management. In desktop mode it works and in android cell mode it seems to work fine too. However, on a Windows tablet, it seems to have a problem ... Basically what I'm trying to do is display a modal in bootstrap 4. But when on the tablet I zoom, my modal s really big and out of my screen. On the android mobile, I remove the zoom before displaying the modal but on the Windows tablet I am unable to reproduce the same behavior.
       
      My toggle function to reset zoom before display modal  ( Yeah it maybe sketches but I'm not find other solutions)
      function resetZooming() { if (zoomOut) { $('meta[name=viewport]').attr('content', 'width=device-width, initial-scale=1.0, maximum-scale=1'); setTimeout(resetZooming, 1000); zoomOut = false; }else{ $('meta[name=viewport]').attr('content', 'width=device-width, initial-scale=1.0'); zoomOut = true; } } And I call this function under my event
      $("#modalCreationForm").modal("show"); resetZooming();  
      If you have any ideas
      Thank you
    • By Chimp
      The DOM allows to do anything with elements and their contents, but first we need to reach the corresponding DOM object, get it into a variable, and then we are able to modify it. *
      Well, this little tool (although it is not very nice aesthetically) allows you to get visually a "selector" usable to reference DOM objects.
      Once you have the "selector" of an element you can pass it to the javascript querySelector() function that will return a reference to that element.
      To use this tool you have to:
      1) open the web page you want to inspect into IE browser
      2) run this script (if it find more instances of IE running, it allows you to chose one)
      3) move the mouse over the browser. The "selector" of the element below the pointer is catched automatically while hovering. To copy the selector in the clipboard just right click on the element.
      As you can see, while hovering, the element pointed by the mouse is highlighted with a thin red dotted frame to allow you to better "take aim"
      when the selector is copied to the clipboard a little acoustic signal is emitted as a confirm, then you can paste it in your listing where you need it.
      I hope it can come in handy and save you time when you need to automate a site .... have fun (debugged on Sept. 30 2018)
      #include <IE.au3> #include <GUIConstantsEx.au3> #include <GuiListBox.au3> #include <WindowsConstants.au3> #include <Misc.au3> ; for _IsPressed (23 END key) Global $hDLL = DllOpen("user32.dll") ; following global variables are automatically updated by events from the browser ; ------------------------------------------------------------------------------------- Global $g_iMouseX, $g_iMouseY ; coordinates of the mouse while mooving over the browser Global $bCopySelector = False ; becomes True when you right click on wanted element ; ------------------------------------------------------------------------------------- Global $oIE = _Get_IE() ; get IE instance to inspect If IsObj($oIE) Then $hIE = _IEPropertyGet($oIE, "hwnd") WinActivate($hIE) _InspectElements() EndIf DllClose($hDLL) Exit Func _InspectElements() ; it uses the global variable $oIE as source ; --- set IE to interact with AutoIt --- Local $oDocument Do ; wait for document Sleep(250) $oDocument = $oIE.document Until IsObj($oDocument) Local $oWindow = $oDocument.ParentWindow ; create a reference to the javascript eval method ; in the body section of the dovument $oWindow.setTimeout("document.body.JSeval = eval; ", 0) ; attach the $JSeval variable to the javascript eval method Local $JSeval Do $JSeval = Execute('$oIE.Document.body.JSeval') Until IsObj($JSeval) ; --------------------------------------------- ; Inject Javascript functions/elements to $oIE ; --------------------------------------------- ; Get the DOM path of an element (a CSS selector) ; ----------------------------------------------- ; This javascript function returns the CSS selector of the passed element. ; You can then use the returned path to get a reference to the pointed ; element by the QuerySelector() javascript function ; function copied from the following link: ; https://stackoverflow.com/questions/5728558/get-the-dom-path-of-the-clicked-a ; see answer by "Aleksandar Totic" (thanks to him) Local $sJScript = "" & _ " function getDomPath(el) {" & _ " if (!el) {" & _ " return;" & _ " }" & _ " var stack = [];" & _ " var isShadow = false;" & _ " while (el.parentNode != null) {" & _ " var sibCount = 0;" & _ " var sibIndex = 0;" & _ " for ( var i = 0; i < el.parentNode.childNodes.length; i++ ) {" & _ " var sib = el.parentNode.childNodes[i];" & _ " if ( sib.nodeName == el.nodeName ) {" & _ " if ( sib === el ) {" & _ " sibIndex = sibCount;" & _ " }" & _ " sibCount++;" & _ " }" & _ " }" & _ " var nodeName = el.nodeName.toLowerCase();" & _ " if (isShadow) {" & _ " nodeName += ""::shadow"";" & _ " isShadow = false;" & _ " }" & _ " if ( sibCount > 1 ) {" & _ " stack.unshift(nodeName + ':nth-of-type(' + (sibIndex + 1) + ')');" & _ " } else {" & _ " stack.unshift(nodeName);" & _ " }" & _ " el = el.parentNode;" & _ " if (el.nodeType === 11) {" & _ " isShadow = true;" & _ " el = el.host;" & _ " }" & _ " }" & _ " stack.splice(0,1);" & _ " return stack.join(' > ');" & _ " }" ; more infos here: https://www.kirupa.com/html5/finding_elements_dom_using_querySelector.htm ; Inject the above javascript function contained in the $sJScript variable into the document _JS_Inject($oIE, $sJScript) Local $_getDomPath ; a reference to call above function from AutoIt Do Sleep(250) $_getDomPath = $jsEval("getDomPath") Until IsObj($_getDomPath) ; ; ------------------- ; hook some IE events ; ------------------- Local $oEventObjects[2], $oEventsSource $oEventsSource = $oIE.document.documentElement ; element we want catch events from ; https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa769636(v=vs.85) $oEventObjects[0] = ObjEvent($oEventsSource, "_HTMLElementEvents2_", "HTMLElementEvents2") ; https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa768283(v%3dvs.85) $oEventObjects[1] = ObjEvent($oIE, "_IEEvent_", "DWebBrowserEvents2") ; open a GUI where to show some element's properties ; -------------------------------------------------- Local $hGUIMain = GUICreate("Info", 500, 140, -1, -1, -1, $WS_EX_TOPMOST) Local $hProperties = GUICtrlCreateEdit("", 0, 0, 500, 140) GUICtrlSetFont(-1, 9, -1, -1, "Courier New") GUISetState() ;Show GUI ; -------------------------------------------------- ; --------- ; Main loop ; --------- Local $iMouseX, $iMouseY, $oElement, $oNewElement, $sSelector Local $oGotElement, $sElementInfos Local $sSaved_StyleOutline, $sSaved_StyleOutline2 ; Loop until the user exits. While IsObj($oIE) Switch GUIGetMsg() Case $GUI_EVENT_CLOSE ExitLoop ; ---> end EndSwitch If ($g_iMouseX <> $iMouseX) Or ($g_iMouseY <> $iMouseY) Then $iMouseX = $g_iMouseX $iMouseY = $g_iMouseY ; $oElement = $oIE.document.elementFromPoint($iMouseX, $iMouseY) ; <-- this way is slower $oNewElement = $JSeval('document.elementFromPoint(' & $iMouseX & ',' & $iMouseY & ');') If $oNewElement <> $oElement Then If IsObj($oElement) Then $oElement.style.outline = $sSaved_StyleOutline $oElement = $oNewElement ; $bSelfie = False ; $iSelf_Timer = TimerInit() $sSaved_StyleOutline = $oElement.style.outline ; save new element's original outline style $sSelector = $_getDomPath($oElement) ; get CSS path If $sSelector <> "" Then ; We could use the $oNewElement, but just to proof that $sSelector is OK ; we get again a reference to the new pointed element using it's $sSelector $oGotElement = $JSeval('document.querySelector("' & $sSelector & '");') ; <-- how to use a selector $oGotElement.style.outline = "1px dashed red" ; mark new pointed element ; https://css-tricks.com/ $sElementInfos = "" & _ "nodeName: " & $oGotElement.nodeName & @CRLF & _ "id: " & $oGotElement.getAttribute('id') & @CRLF & _ "class: " & $oGotElement.getAttribute('class') & @CRLF & _ "type: " & $oGotElement.getAttribute('type') & @CRLF & _ "---------" & @CRLF & _ $sSelector ControlSetText($hGUIMain, "", $hProperties, $sElementInfos) EndIf EndIf EndIf ; $bCopySelector is setted to True by the right-click event on an element, ; see Volatile Func _HTMLElementEvents2_onContextmenu($oEvent) near script bottom If $bCopySelector And ($sSelector <> "") Then ; And (TimerDiff($iSelf_Timer) > $bSelfie_Delay) Then ; $sSaved_StyleOutline2 = $oGotElement.style.outline $oGotElement.style.outline = "5px dotted #ff0066" ; mark copied element ClipPut($sSelector) $sElementInfos &= @CRLF & "selector copied to ClipBoard" ControlSetText($hGUIMain, "", $hProperties, $sElementInfos) Beep(2000, 50) $bCopySelector = False Sleep(250) $oGotElement.style.outline = $sSaved_StyleOutline2 ; ToolTip('') EndIf If _IsPressed("23", $hDLL) Then ; END key pressed If IsObj($oElement) Then $oElement.style.outline = $sSaved_StyleOutline WinActivate($hGUIMain) ; WinSetState($hGUIMain, "", @SW_SHOW) $aWin = WinGetPos($hGUIMain) MouseMove($aWin[0] + $aWin[2] / 2, $aWin[1] + $aWin[3] / 2, 0) EndIf WEnd ; the end ; ------------------------------------------ For $i = 0 To UBound($oEventObjects) - 1 ; Tell IE we don't want to receive events. $oEventObjects[$i] .Stop $oEventObjects[$i] = 0 Next $oIE = 0 ; Remove IE from memory GUIDelete($hGUIMain) ; Remove GUI ; ------------------------------------------ EndFunc ;==>_InspectElements Func _Get_IE() ; Example 5 from the _IEAttach help ; Create an array of object references to all current browser instances ; The first array element will contain the number of instances found Local $aIE[1] $aIE[0] = 0 Local $i = 1, $oIEx While 1 $oIEx = _IEAttach("", "instance", $i) If @error = $_IEStatus_NoMatch Then ExitLoop ReDim $aIE[$i + 1] $aIE[$i] = $oIEx $aIE[0] = $i $i += 1 WEnd If $aIE[0] > 0 Then If $aIE[0] = 1 Then Return $aIE[1] ; only one IE is running, return this then ; ; Create a little list box to choose the IE instance from Local $hChoose_IE = GUICreate("IE Instances", 600, 350) Local $Label1 = GUICtrlCreateLabel($aIE[0] & " running Instances of IE browser found, click the one you want to attach to then click on 'ok'", 5, 5, 590, 20) Local $List1 = GUICtrlCreateList("", 5, 30, 590, 300, BitOR($LBS_STANDARD, $LBS_EXTENDEDSEL)) Local $hButton_choosed = GUICtrlCreateButton("OK", 5, 325, 590, 20) For $i = 1 To $aIE[0] GUICtrlSetData($List1, $i & ") " & _IEPropertyGet($aIE[$i], "locationurl")) Next GUISetState(@SW_SHOW) While 1 ; wait for a selection Switch GUIGetMsg() Case $GUI_EVENT_CLOSE GUIDelete($hChoose_IE) Return False Case $hButton_choosed $aSelected = _GUICtrlListBox_GetSelItems($List1) If $aSelected[0] Then GUIDelete($hChoose_IE) Return $aIE[$aSelected[1] + 1] Else MsgBox(0, "Info", "Please select an item") EndIf EndSwitch WEnd Else MsgBox(0, 'error', "Sorry" & @CRLF & @CRLF & "no running IE instances found") EndIf EndFunc ;==>_Get_IE ; this function creates a javascript script into the html document ; of the passed $oIE object using the createElement method. Func _JS_Inject($oIE, $sJScript, $bIsUrl = False) ; ; get a reference to the document object Local $objDocument = $oIE.document ; Local $oScript = $objDocument.createElement('script') ; $oScript.type = 'text/javascript' If $bIsUrl Then $oScript.src = $sJScript ; works if $sJScript is a link to a js listing (url) Else ; (https://stackoverflow.com/questions/35213147/difference-between-text-content-vs-inner-text) ; $oScript.innerText = $sJScript $oScript.TextContent = $sJScript ; works if $sJScript contains the listing itself EndIf ; $objDocument.getElementsByTagName('head').item(0).appendChild($oScript) ; $objDocument.getElementsByTagName('head').item(0).removeChild($oScript); ; EndFunc ;==>_JS_Inject ; ------------------------------------------------------------------- ; following function(s) are called by registered $oIE elements events ; ------------------------------------------------------------------- ; ; The function automatically fired by an event ; will receive as parameter an Event Obj. ; This obj has properties related to ; the object that fired the event. ; See following link: ; https://msdn.microsoft.com/en-us/library/aa703876(v=vs.85).aspx ; function called by the mousemove event ; we use this to update 2 global variables: Volatile Func _HTMLElementEvents2_onMousemove($oEvent) $g_iMouseX = $oEvent.clientX $g_iMouseY = $oEvent.clientY EndFunc ;==>_HTMLElementEvents2_onMousemove ; function called by the contextmenu event ; we use this to update 1 global variable ; and we also neutralize this event: Volatile Func _HTMLElementEvents2_onContextmenu($oEvent) $oEvent.cancelBubble = True ; event propagation cancelled $oEvent.returnValue = False ; prevent default behaviour $bCopySelector = True ; when True, selector will be copied to clipboard in main loop EndFunc ;==>_HTMLElementEvents2_onContextmenu ; https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa768280%28v%3dvs.85%29 Func _IEEvent_BeforeNavigate2($oIEpDisp, $sIEURL, $iIEFlags, $sIETargetFrameName, $sIEPostData, $iIEHeaders, $bIECancel) ;ConsoleWrite("Debug: navigate away cancelled." & @CRLF) ; https://stackoverflow.com/questions/6526876/how-to-cancel-or-dispose-current-navigation-at-webbrowser-element $oIE.stop EndFunc ;==>_IEEvent_BeforeNavigate2 Here is a simple example on how a "selector" can be used in AutoIt.
      suppose we want automate the login to the AutoIt site with our username and password.
      I've already prepared a very simple "template" where are missing some important parts without which the script can't work. Missing parts are the references to the elements of the AutoIt web page that we have to manage by our script.
      well, here is where the tool I have just posted here above comes to our help.
      follow this steps:
      1) in IE open the AutoIt site at the forum page (https://www.autoitscript.com/forum/)
      2) run the above tool (select the IE instance and/or bring it to front if needed)
      3) when the script is "ready", move the mouse over the "Existing user? Sign In" string and right click the mouse button. Doing so the "selector" of that element is copied to the clipboard. Now we can paste it in our AutoLogIt.au3 script as value of the $sSignIn variable.
      4) now click on the "Existing user? Sign In"  to open the "Sig In" session from where we will copy selectors of each of the 2 input box Username and Password, in the same way as we have already done in step 3, and paste those selectors to the $sInputUserId and $sInputPasswd variables respectively.
      5) do the same for the "Sign In" Button and paste it's selector to the $sSignInButn variable
      6) of course also fill the $sMyUserId and $sMyPasswd variables with your data.
      That's It. Run the AutoLogIt script and it should Log you on automatically to the forum.
      AutoLogIt.au3
      #include <ie.au3> $sMyUserId = "" ; <-- your userid here $sMyPasswd = "" ; <-- your password here ; set selectors here $sSignIn = "" ; <-- SigIn element selector here $sInputUserId = "" ; <-- UserId input selector here $sInputPasswd = "" ; <-- Password input selector here $sSignInButn = "" ; <-- Sig In button selector here $oIE = _IECreate("https://www.autoitscript.com/forum/") ; here is how to use the QuerySelector javascript function $hDOM_Element = $oIE.document.QuerySelector($sSignIn) ; get the "sign in" link element ; perform a click action on the above element $hDOM_Element.click() ; or _IEAction($hDOM_Element, "click") as well ; fill the username input $hDOM_Element = $oIE.document.QuerySelector($sInputUserId) $hDOM_Element.value = $sMyUserId ; fill the password input $hDOM_Element = $oIE.document.QuerySelector($sInputPasswd) $hDOM_Element.value = $sMyPasswd ; .... or also using the dot notation directly .... $oIE.document.QuerySelector($sSignInButn).click() Sleep(5000) ; this should logout $sMenu = "body > div:nth-of-type(2) > header > div > ul > li:nth-of-type(6) > a:nth-of-type(2)" $oIE.document.QuerySelector($sMenu).click() $sLogOut = "body > ul > li:nth-of-type(9) > a" $oIE.document.QuerySelector($sLogOut).click()  
×
×
  • Create New...