我正在手动向网站发送请求,并在WebView
中渲染响应的正文。为此,我使用了WebView
的引擎的loadContent
方法:
String bodyOfResponse = ...;
myWebView.getEngine().loadContent(bodyOfResponse);
问题是WebView
从String
而不是位置中获取其内容,因此它不知道如何解决我给它的内容的HTML中的相对链接:
<span onclick="document.location.href='/'">Home</span>
WebView
找不到'/'
所指的内容,因为我没有通过URL提供WebView
内容。有没有办法可以设置当前文档的位置(或我听到的baseuri(,以便我的WebView
知道如何解决相对路径?(我知道原始服务器的URL。(
我已经看到,使用内容中的绝对位置而不是相对的位置足以使WebView
在位置加载数据,但是我无法修改服务器,并且它为我提供了绝对的服务所有HTML页面中的URL。
如果我只能webEngine.setBasePath(serverURL)
...但是我不能。:(
等待WebEngine的文档完成加载,然后添加A&lt; base&gt;<head>
中的元素:
String newBaseURL = "http://www.example.com/app";
myWebView.getEngine().getLoadWorker().stateProperty().addListener(
(obs, old, state) -> {
if (state == Worker.State.SUCCEEDED) {
Document doc = myWebView.getEngine().getDocument();
XPath xpath = XPathFactory.newInstance().newXPath();
try {
Element base = (Element) xpath.evaluate(
"//*[local-name()='head']/*[local-name()='base']",
doc, XPathConstants.NODE);
if (base == null) {
Element head = (Element) xpath.evaluate(
"//*[local-name()='head']",
doc, XPathConstants.NODE);
if (head == null) {
head = doc.createElement("head");
Element html = (Element) xpath.evaluate(
"//*[local-name()='html']",
doc, XPathConstants.NODE);
html.insertBefore(head, html.getFirstChild());
}
base = doc.createElement("base");
head.insertBefore(base, head.getFirstChild());
}
base.setAttribute("href", newBaseURL);
} catch (XPathException e) {
e.printStackTrace();
}
}
});
myWebView.getEngine().loadContent(bodyOfResponse);