How to get a "global" variable from html/javascript in haxe?

706 views
Skip to first unread message

Freewind

unread,
Jan 14, 2013, 1:42:09 AM1/14/13
to haxe...@googlegroups.com
The html:

<html>
    <script>
       hello = "world";
    </script>
    <script src="script_generated_by_haxe.js"></script>
</html>

You can see there is a "hello" variable which is in global "window" of the html. But how can I get it in haxe?

I tried:

    js.Lib.window.hello

But it reports that "js.Window has no field hello".

Jason O'Neil

unread,
Jan 14, 2013, 2:18:08 AM1/14/13
to haxe...@googlegroups.com
If you put the keyword "untyped" in front of it, then the Haxe compiler will allow it:

    var h:String = untyped js.Lib.window.hello;

Or you could also use Reflect

    var h = Reflect.field(js.Lib.window, "hello");

but neither of these are type safe... so be careful because the compiler won't warn you if the variable is missing etc :)

If you want to do something more complicated, and make sure it's type-safe, you can generate an extern for the Javascript you're accessing.  You can have a look at the details on this wiki page: http://haxe.org/doc/js/extern_libraries


Freewind

unread,
Jan 14, 2013, 2:55:01 AM1/14/13
to haxe...@googlegroups.com
Thanks for the usage of "untyped"!

Eric Priou

unread,
Jan 14, 2013, 7:28:19 AM1/14/13
to haxe...@googlegroups.com
@expose should be usded instead of untyped, ain't it?

I wonder if such kind of construct could be done easily in haxe too ?

var namespace =  namespace || {};
namespace.values = (
function()
{
return {
myVal : []
};
}
)();

A way to expose hash values in namespaces 

Is it the case of modifying the js output + a meta ?

Thanks,
---
Eric Priou aka erixtekila

Reply all
Reply to author
Forward
0 new messages