ocamljs-of-ocaml

How do I write console.log in js_of_ocaml?


How do I write console.log in js_of_ocaml? print_endline might go to the console, but I want access to trace, error, etc. Can I just define console as an external object?

This does not work for me:

let console = Js.Unsafe.global##console

Fails with:

TypeError: N.console is not a function test.js:255:30

This fails with the same error:

class type console = object
  method log : Js.js_string Js.t -> unit Js.meth
end

let _ =
  let console : console = Js.Unsafe.global##console in
  let here : Js.js_string Js.t = Js.string "here" in
  console#log here

Solution

  • The JavaScript console object is inside the Firebug module, API here: https://ocsigen.org/js_of_ocaml/3.5.0/api/js_of_ocaml/Js_of_ocaml/Firebug/class-type-console/index.html

    Example:

    open Js_of_ocaml
    open Js
    let here : js_string t = string "here" in 
    Firebug.console##log here;
    

    NB: Just writing Firebug.console##log "here" will dump an object, not the JavaScript string "here".