I am trying to inject a global JavaScript function into a webview before the page loads. I have a function called testJS
that I am injecting in. In my WebViewClient I am doing the following
private String getJS() {
return "javascript:function testJS() { return { test: 'Hello World' };}";
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
view.loadUrl(getJS());
}
When I inspect the page, window.testJS
is undefined.
If I do the following, window.testJS
has the correct function in the webview but it is not loaded early enough so does not work correctly.
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl(getJS());
}
In iOS I could do the equivalent with injecting a script atDocumentStart
and it works the way I expect it to.
let userScript = WKUserScript(
source: scriptContent!,
injectionTime: WKUserScriptInjectionTime.atDocumentStart,
forMainFrameOnly: false)
contentController.addUserScript(userScript)
Is there another way I can achieve this in an android WebView? It works onPageFinished but not onPageStarted.