Inject a JavaScript API on everypage loaded on WebView

时光怂恿深爱的人放手 提交于 2019-12-13 07:32:16

问题


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>


来源:https://stackoverflow.com/questions/13535759/inject-a-javascript-api-on-everypage-loaded-on-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!