简体   繁体   English

如何在RubyRacer中评估HTML DOM对象(如“文档”)

[英]How to evaluate a HTML DOM object (like “document”) in RubyRacer

RubyRacer allows me to easily execute javascript code within a ruby environment, like so: RubyRacer允许我在ruby环境中轻松执行javascript代码,如下所示:

cxt = V8::Context.new
wanted_output = cxt.eval(whatever_javascipt_code)

How does one have to do it when objects like "document" are involved, like for example in the follwing code snippet? 当涉及“文档”之类的对象时(例如,在下面的代码片段中),该如何做? (In other words, how can I generate the output of "document.write" in this case?) (换句话说,在这种情况下,如何生成“ document.write”的输出?)

<script language="javascript" type="text/javascript">
  A="some_string";
  B="some_other_string";
  C="";

  for(j=0;j<B.length;j++){
    C+=A.charAt(B.charCodeAt(j)-48);
  }document.write(C);
</script>

Simply evaluating the script above would result in the error message: 仅评估上面的脚本将导致错误消息:

"V8::JSError: document is not defined"

Thanks a lot for any hints! 非常感谢您的任何提示!

Assuming that the variable 'script' contains the javascript code mentioned above: 假设变量“脚本”包含上述javascript代码:

cxt = V8::Context.new
script.insert(0, "output=''")

document_write_count = script.scan('document.write(').count
remaining = script
document_write_count.times do |i|
  document_write_clause_content = remaining.partition('document.write(')[2].partition(')')[0]
  document_write_clause = "document.write(#{document_write_clause_content})"
  document_write_clause_replacement = "output+=#{document_write_clause_content}"
  script.gsub!(document_write_clause, document_write_clause_replacement)
  remaining = remaining.rpartition(document_write_clause_replacement)[2]
end

script.insert(-1, "output;")

wanted_output = cxt.eval("#{script}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM