Search code examples
androidandroid-webviewscorm

Inject a JavaScript API on everypage loaded on WebView


I am coding a offline Scorm player, so need to inject an JavaScript API on every html page loaded by the WebView instance. I tried to use a frame-set approach, but WebView doesnt behave the way it should (besides that, its deprecated in HTML5). How can I achieve this? I need the script to be injected before the page loads, because those html pages will consume the API on the body onLoad event..

When trying to to override the 'onPageStarted' WebViewClient method, although the event was fired, the JS code injected could not be reached.

Thanks in advance, Pablo


Solution

  • you can inject javascript everpageload by using below code, hope it helps

    final WebView webview = (WebView)findViewById(R.id.webView1);  
            /* JavaScript must be enabled if you want it to work, obviously */  
            webview.getSettings().setJavaScriptEnabled(true);  
    
            /* WebViewClient must be set BEFORE calling loadUrl! */  
            webview.setWebViewClient(new WebViewClient() {  
                @Override  
                public void onPageFinished(WebView view, String url)  
                {  
    
                    webview.loadUrl("javascript:myFunction()");  
                }  
            });  
    
            webview.loadUrl("http://code.google.com/android"); 
    
    HTML 
    
    <!DOCTYPE html>
    <html>
    <head>
    <script>
    function myFunction()
    {
       alert("Hello World!");
    }
    </script>
    </head>
    
    <body>
    <button onclick="myFunction()">Try it</button>
    </body>
    </html>