Webbrowser (Shell.Explorer): Adding item via AHK to an JS-Array of objects

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
hotkeyguy
Posts: 170
Joined: 11 Oct 2014, 12:22

Webbrowser (Shell.Explorer): Adding item via AHK to an JS-Array of objects

01 Nov 2019, 16:29

Hello,

I have a crazy problem. When I try to add an item with Object.push( AHK_NewObject ) to an existing JS-Array of objects, the added object is empty. JS-Array of objects in my <script>-section like:

Code: Select all

var JS_ArrayOfObjects = [
  { id: 1, color: "green" } ,
  { id: 2, color: "yellow"}
] ;
AHK-code:

Code: Select all

AHK_ArrayOfObjects := WB.document.parentWindow.JS_ArrayOfObjects
AHK_NewObject := { id: 3, color: "red" }
AHK_ArrayOfObjects.push( AHK_NewObject  )
The resulting JS_ArrayOfObjects is

Code: Select all

[
  { id: 1, color: "green" } ,
  { id: 2, color: "yellow"} ,
  {}
] ;
Any hints are highly appreciated!

Edit: Webbrowser in IE11-mode!


Many thanks and greetings
hotkeyguy
teadrinker
Posts: 4331
Joined: 29 Mar 2015, 09:41
Contact:

Re: Webbrowser (Shell.Explorer): Adding item via AHK to an JS-Array of objects

01 Nov 2019, 18:28

No, you can't push ahk-objects to js-objects, these are completely different objects. The only way is to turn ahk-object to the js-like string, and then push this string to js-object in the js context, eg:

Code: Select all

script =
(
var JS_ArrayOfObjects = [
  { id: 1, color: "green" } ,
  { id: 2, color: "yellow"}
] ;
)

JS := GetJS()
JS.eval(script)

AHK_NewObject := { id: 3, color: "red" }
jsStr := ObjToString(AHK_NewObject)

JS.eval("JS_ArrayOfObjects.push(" . jsStr . ")")
JS.eval("alert(JS_ArrayOfObjects[2].color)")

GetJS() {
   static doc := ComObjCreate("htmlfile")
        , _ := doc.write("<meta http-equiv=""X-UA-Compatible"" content=""IE=11"">")
        , JS := doc.parentWindow
   Return JS
}

ObjToString(obj) {
   if IsObject( obj ) {
      isArray := true
      for key in obj {
         if IsObject(key)
            throw Exception("Invalid key")
         if !( key = A_Index || isArray := false )
            break
      }
      for k, v in obj
         str .= ( A_Index = 1 ? "" : "," ) . ( isArray ? "" : """" . k . """:" ) . ObjToString(v)

      Return isArray ? "[" str "]" : "{" str "}"
   }
   else if !(obj*1 = "" || RegExMatch(obj, "\s"))
      Return obj
   
   for k, v in [["\", "\\"], [A_Tab, "\t"], ["""", "\"""], ["/", "\/"], ["`n", "\n"], ["`r", "\r"], [Chr(12), "\f"], [Chr(08), "\b"]]
      obj := StrReplace( obj, v[1], v[2] )

   Return """" obj """"
}
User avatar
kczx3
Posts: 1640
Joined: 06 Oct 2015, 21:39

Re: Webbrowser (Shell.Explorer): Adding item via AHK to an JS-Array of objects

01 Nov 2019, 19:57

Yeah, when you send an ahk object to JS that is exactly what you get in JS, an AHK object. You can still reference the keys though

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: filipemb and 304 guests