Jump to content

Autoit <-> Javascript roundtrip


Gianni
 Share

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
Link to comment
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

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

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

Link to comment
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

Link to comment
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:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor 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 * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

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 * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

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 TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

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 *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"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: 2023-04-24

Link to comment
Share on other sites

  • 10 months later...

.... 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

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

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

Link to comment
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

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

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

Link to comment
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
 Share

×
×
  • Create New...