Brr: is it possible to convert a string to an Object URL?

In JS, we can do something like:

blob = new Blob(["Hello World"], {type: "application/javascript"})

This allows us to encode a string into an Object URL, so that requesting the URL return the string (as a blob).

Is there a way to do this in Brr? I can not find createObjectURL while grepping through the codebase.

I don’t think there’s a binding to that particular function (I don’t see anything in Brr.Uri), so you’ll have to do it yourself. Something along the lines of

module Url : sig
  val create_object_url : Brr.Blob.t -> Jstr.t
end = struct
  let url = Jv.get "URL"

  let create_object_url blob = url "createObjectURL" [| (Brr.Blob.to_jv blob) |]
    |> Jv.to_jstr

let () =
  let init = Brr.Blob.init ~type':(Jstr.v "application/javascript") () in
  let s = Url.create_object_url (Brr.Blob.of_jstr ~init (Jstr.v "Hello World")) in
  Brr.Console.log [ s ]
1 Like

Dumb (on my part) question: independently, I was trying:

external create_object_url_from_blob : Brr.Blob.t -> Brr.Uri.t = "URL.createObjectURL"

however, when I try to call it, I get a runtime error of:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'createObjectURL')

It appears ‘URL’ is undefined for some reason in this case. What am I doing wrong ?

The external keyword is not meant to be used in that way. In “normal” OCaml code it is used to call C functions. When compiling to JS with jsoo, you have to follow this guidance for writing JS stubs. Typically you won’t need to use it. Exceptions are when you are trying to provide JS support to an OCaml library that uses C code. For example, see Cstruct ocaml-cstruct/cstruct.js at main · mirage/ocaml-cstruct · GitHub

1 Like