使用Rhino的java调用决战
我想使用Rhino使用showdownjs javascript标记库
它的用法如下:
var Showdown = require('showdown');
var converter = new Showdown.converter();
converter.makeHtml('#hello markdown!');
// <h1 id="hellomarkdown">hello, markdown</h1>
所以我要摊牌了。js文件(https://raw.githubusercontent.com/showdownjs/showdown/master/compressed/Showdown.js),我将如何调用这个makeHTML
方法,同时向它传递一个我在jvm端拥有的参数
我在网上找到了以下代码片段:
import org.mozilla.javascript.Scriptable
import org.mozilla.javascript.ScriptableObject
import org.mozilla.javascript.{Context, Function}
import java.io.InputStreamReader
class Showdown {
def markdown(text: String): String = {
// Initialize the Javascript environment
val ctx = Context.enter
try {
val scope = ctx.initStandardObjects
// Open the Showdown script and evaluate it in the Javascript
// context.
val showdownURL = getClass.getClassLoader.getResource("showdown.js")
val stream = new InputStreamReader(showdownURL.openStream)
ctx.evaluateReader(scope, stream, "showdown", 1, null)
// Instantiate a new Showdown converter.
val converterCtor = ctx.evaluateString(scope, "Showdown converter", "converter", 1, null).asInstanceOf[Function]
val converter = converterCtor.construct(ctx, scope, null)
// Get the function to call.
val makeHTML = converter.get("makeHtml", converter).asInstanceOf[Function]
val htmlBody = makeHTML.call(ctx, scope, converter, Array[AnyRef](text))
htmlBody.toString
}
finally {
Context.exit
}
}
}
当我这样使用它时:
val s = new Showdown()
s.markdown("hello")
我得到一个错误:
org.mozilla.javascript.EvaluatorException: missing ; before statement (converter#1)
at org.mozilla.javascript.DefaultErrorReporter.runtimeError(DefaultErrorReporter.java:109)
at org.mozilla.javascript.DefaultErrorReporter.error(DefaultErrorReporter.java:96)
at org.mozilla.javascript.Parser.addError(Parser.java:146)
at org.mozilla.javascript.Parser.reportError(Parser.java:160)
at org.mozilla.javascript.Parser.statementHelper(Parser.java:1266)
at org.mozilla.javascript.Parser.statement(Parser.java:707)
at org.mozilla.javascript.Parser.parse(Parser.java:401)
at org.mozilla.javascript.Parser.parse(Parser.java:338)
at org.mozilla.javascript.Context.compileImpl(Context.java:2368)
at org.mozilla.javascript.Context.compileString(Context.java:1359)
at org.mozilla.javascript.Context.compileString(Context.java:1348)
at org.mozilla.javascript.Context.evaluateString(Context.java:1101)
我以前从未使用过Rhino,所以我不确定问题出在哪里
我的方法中的这条线看起来正确吗
val converterCtor = ctx.evaluateString(scope, "Showdown converter", "converter", 1, null).asInstanceOf[Function]
# 1 楼答案
这应该能奏效
希望有帮助