如何选择动态插入到ScalaJS页面的全局对象

时间:2016-07-19 10:27:08

标签: scala.js

我尝试将Google ReCaptcha脚本插入页面,但我无法选择全局grecaptcha

val script = dom.document.createElement("script").asInstanceOf[HTMLScriptElement]
script.setAttribute("src", "https://www.google.com/recaptcha/api.js")
script.setAttribute("async", "true")

script.onload = { (_: Event) =>
  println(Dynamic.global.selectDynamic("grecaptcha")) // --> got undefined
}

dom.document.body.appendChild(script)

控制台窗口中,我可以获得grecaptcha

grecaptcha

问题是如何选择全局grecaptcha对象?

1 个答案:

答案 0 :(得分:0)

根据this answer in a vanilla JavaScript environment,您只是有一个订购问题。步骤应该是

  1. 将脚本附加到文档
  2. 设置onload事件
  3. 设置src属性
  4. val script = dom.document.createElement("script").asInstanceOf[HTMLScriptElement]
    dom.document.body.appendChild(script)
    script.onload = { (_: Event) =>
      println(Dynamic.global.selectDynamic("grecaptcha"))
    }
    script.setAttribute("src", "https://www.google.com/recaptcha/api.js")
    script.setAttribute("async", "true")