0
我試圖使用的ScriptEngine這裏是我的代碼來調用文檔中的Java「文件」不<eval> ScriptEngine中的Java定義
ScriptEngineManager scriptEngineManager=new ScriptEngineManager();
ScriptEngine scriptEngine=scriptEngineManager.getEngineByName("nashorn");
scriptEngine.eval("function func(){" +
"document.location.href=someUrl;" +
"var text=document.getElementsByTagName('textarea')[0];"}"
);
Invocable invocable= (Invocable) scriptEngine;
((Invocable) scriptEngine).invokeFunction("func");
它拋出一個異常
javax.script.ScriptException: ReferenceError: "document" is not defined in <eval> at line number 1
謝謝,我如何從url加載文件? – DoctorDo
你不需要JavaScript來做到這一點。使用HTTP客戶端(如https://github.com/square/okhttp或https://hc.apache.org/)來下載頁面的原始HTML **。這不會像瀏覽器中所期望的那樣爲您提供頁面的DOM,但是(您也不會在腳本引擎中獲得)。要從原始html文本中獲取DOM,請檢查http://stackoverflow.com/questions/457684/reading-html-file-to-dom-tree-using-java – metlos
謝謝。我想加載文檔並以編程方式爲按鈕添加EventListener,這就是爲什麼我使用JavaScript。 – DoctorDo