我有使用其他JavaScript源代码的JavaScript代码:
<body>
<script src="node_modules/node-vibrant/dist/vibrant.js"></script>
<script type="text/javascript">
function test(src) {
Vibrant.from(src).getPalette(function(err, swatches) {
if (err) throw err;
for (var key in swatches) {
if (key === "Vibrant") {
var swatch = swatches[key];
if (swatch) {
console.log("hex: " + swatch.getHex());
return (swatch.getHex());
}
}
}
});
}
test("Apples.jpg");
</script>
</body>
我想用Java调用这段代码。怎么做?
我试图使用ScriptManager
,但收到的错误是:
窗口未定义
答案 0 :(得分:0)
这应该适合你。
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
// JavaScript code in a String
String script = " function test(src) { Vibrant.from(src).getPalette(function(err, swatches) { if (err) throw err; for (var key in swatches) { if(key==='Vibrant'){ var swatch = swatches[key]; if (swatch) { console.log('hex: ' + swatch.getHex()); return(swatch.getHex()); }} } }); }";
// evaluate script
engine.eval(script);
Invocable inv = (Invocable) engine;
// invoke the global function named "hello"
inv.invokeFunction("test", "Apples.jpg" );