Inject a JavaScript API on everypage loaded on Web

2019-09-12 05:55发布

问题:

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

回答1:

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>