2012-03-21 41 views
1

RubyRacer讓我輕鬆紅寶石環境中執行JavaScript代碼,就像這樣:如何RubyRacer評價一個HTML DOM對象(如「文件」)

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

怎樣纔能有這樣做時,對象像「文檔」都參與其中,例如在以下代碼片段中? (換句話說,我怎樣才能生成「文件撰寫」的輸出在這種情況下?)

<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> 

只需評估上面的腳本將導致錯誤消息:

"V8::JSError: document is not defined" 

由於很多提示!

+0

這是我第一次聽到這種寶石的,它聽起來很有趣。太糟糕了,它不會安裝在Windows上:(( – pguardiario 2012-03-21 14:01:16

+0

是的,得到ubuntu.com :-)) – TomDogg 2012-03-21 14:06:34

回答

0

假設變量「腳本」包含上述的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}")