5

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.

sideshowbob
  • 304
  • 6
  • 23

1 Answers1

-4

First try to allow javascript as a setting feature:

WebSettings webSettings = yourWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

Then:

yourWebView.addJavascriptInterface(new Object(){
       @JavascriptInterface
       public void test(){
           Log.d("JS", "test");
            }
   },"Android");
yourWebview.loadUrl("javascript:functionName(\"" + argument + "\")");

Refer to these questions:

Android Calling JavaScript functions in WebView

Call javascript function in Android WebView

Community
  • 1
  • 1
  • It is enabled. That is not the issue. The issue is the JavaScript is not loaded correctly from onPageStarted. – sideshowbob Apr 17 '17 at 15:12
  • Where does my JavaScript go? What is the point of the interface if you are just loading a javascript function anyways – sideshowbob Apr 17 '17 at 15:50
  • still not what I am asking. The question is about loading JavaScript before the page loads. I am able to load JS in a WebView fine but I need it before the actual webpage is rendered. I need a JS function injected that is called via the page. – sideshowbob Apr 17 '17 at 17:16