参考资料

Mozilla Rhino首页:
http://www.mozilla.org/rhino/java中使用Rhino执行js文件中的function

Rhino 下载java中使用Rhino执行js文件中的function
Rhino 官方文档java中使用Rhino执行js文件中的function

 

test.js

function Transfer(content, baseurl)
{
 //TODO
 var result = "";
 if(content.indexOf('<body>') > -1 && content.indexOf('</body>') > -1)
 {
     result = content.substring(content.indexOf('<body>') + 6,content.indexOf('</body>'));
 }
 return result;
}

 

java code

@Test
 public void ExecuteJavascriptByRhino() throws BSFException, FileNotFoundException, IOException
 {
  
  String jsPath = "c:\\test.js";
        String jsFunction = "Transfer";
        String content = "<html><head><title>测试测试</title></head><body><div>aaaa</div>html body ,hahahaha ,垃圾</body></html>";
        String baseurl = "http://www.edzh.com";
       
        //开始调用javascript函数
        Context cx = Context.enter();
        try {
            Scriptable scope = cx.initStandardObjects();
            cx.evaluateReader(scope, new java.io.FileReader(jsPath), "<cmd>", 1, null);

            Object fObj = scope.get(jsFunction, scope);
            if (!(fObj instanceof Function)) {
                System.out.println("找不到方法" +jsFunction);
            } else {
                Object functionArgs[] = { content, baseurl};
                Function f = (Function)fObj;
                Object result = f.call(cx, scope, scope, functionArgs);
                System.out.println("返回结果:"+Context.toString(result));
            }
        } finally {
            Context.exit();
        }
 }

相关文章:

  • 2022-02-16
  • 2022-12-23
  • 2021-05-17
  • 2021-06-21
  • 2022-12-23
  • 2022-12-23
  • 2021-12-01
猜你喜欢
  • 2021-11-12
  • 2021-11-30
  • 2021-11-01
  • 2022-12-23
  • 2022-01-08
  • 2021-12-06
  • 2022-02-26
相关资源
相似解决方案