Skip to content

Commit

Permalink
fix links via mutation observer
Browse files Browse the repository at this point in the history
  • Loading branch information
obydog002 committed Dec 4, 2024
1 parent 7047d4e commit 532a18e
Showing 1 changed file with 32 additions and 7 deletions.
39 changes: 32 additions & 7 deletions src/main/java/com/faforever/client/fx/WebViewConfigurer.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
Expand Down Expand Up @@ -55,13 +58,35 @@ public void configureWebView(WebView webView) {
themeService.registerWebView(webView);

((JSObject) engine.executeScript("window")).setMember(JAVA_REFERENCE_IN_JAVASCRIPT, browserCallback);
engine.executeScript(
"document.onclick = function (elt) {" +
" document.querySelectorAll(\"a[target]\").forEach(e => {" +
" if (!e.href.includes(\"javascript\")) " +
" e.href = \"javascript:java.openUrl('\" + e.href + \"')\"" +
" });" +
"}");
Document document = webView.getEngine().getDocument();
if (document == null) {
return;
}

NodeList nodeList = document.getElementsByTagName("a");
for (int i = 0; i < nodeList.getLength(); i++) {
Element link = (Element) nodeList.item(i);
String href = link.getAttribute("href");
link.setAttribute("href", "javascript:java.openUrl('" + href + "');");
}

engine.executeScript("""
let obs = new MutationObserver((mutations, observer) => {
const addedNodes = mutations.flatMap(mut => Array.from(mut.addedNodes));
const links = [];
for (const node of addedNodes) {
if (node?.querySelectorAll) {
links.push(...Array.from(document.querySelectorAll("a")));
}
}
for (const elt of links) {
if (!elt.href.includes("javascript:java.openUrl")) {
elt.setAttribute("href", "javascript:java.openUrl('" + elt.href + "')");
}
}
});
obs.observe(document.body, {subtree:true, childList:true});
""");
});
}
}

0 comments on commit 532a18e

Please sign in to comment.