import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;

public class Main {

    public static void main(String[] args) {

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        try {
            FileReader reader = new FileReader("C:/yourfile.js");
            engine.put("urlfromjava", "http://www.something.com/?asvb");
            engine.eval(reader);
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

现在,yourfile.js包含以下行
function urlget(url)
{
    print("URL:"+url);
    var loc = window.open(url);
    var link = document.getElementsByTagName('a')["61"].href;
    return ("\nLink is: \n"+link);

}
var x = urlget(urlfromjava);
print(x);

我得到了错误
"javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "window" is not defined"

如何打开URL并从Java获取其链接?

最佳答案

根据documentation:



由于您没有在浏览器中执行脚本,因此未定义window对象。

您可以使用URL / URLConnecion类读取URL,并将其提供给ScriptEngine。 There is a tutorial here

08-05 06:46