Reputation: 129
I want my webview insert sort of javascript after a page has been loaded. However, the javascript I added has never been executed:( what can I do on this?
mWebView = findViewById(R.id.webview);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished (WebView view, String url) {
super.onPageFinished(view, url);
Log.d("WebClient", "onPageFinished");
view.loadUrl("javascript:(function(){"+
"aTagElements=document.getElementsByTagName('a');" +
"randromElement=aTagElements[Math.floor(Math.random() * aTagElements.length)];"+
"clickEvent=document.createEvent('HTMLEvents');"+
"clickEvent.initEvent('click',true,true);"+
"randromElement.dispatchEvent(clickEvent);" +
"alert('event dispatched.');"+ //<---not called
"})()");
}
});
Even if I comment out all the scripts except the alert
line, still nothing happens.
Upvotes: 1
Views: 541
Reputation: 3149
You are mixing views. So change
super.onPageFinished(view, url);
To
super.onPageFinished(mWebView, url);
Upvotes: 2
Reputation: 10234
Try using evaluvateJavascript
, loadUrl
will work only in old version.
webview.evaluateJavascript("(function() { "javascript:(function(){"+
"aTagElements=document.getElementsByTagName('a');" +
"randromElement=aTagElements[Math.floor(Math.random() * aTagElements.length)];"+
"clickEvent=document.createEvent('HTMLEvents');"+
"clickEvent.initEvent('click',true,true);"+
"randromElement.dispatchEvent(clickEvent);" +
"alert('event dispatched.');";
Upvotes: 1
Reputation: 1314
You will have to use like this on application side
mWebView .addJavascriptInterface(new WebAppInterface(this), "Android");
and will have to implement method on php side where actually this method will be trigger
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
on PHP Side implement like this
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
For a complete reference, you can go through on this link
Whenever you will click the button on webView
then you will get a message
Upvotes: 2
Reputation: 1355
Try the below solution may it works for you.
WebSettings webSettings = webView.getSettings();
webSettings.setDefaultTextEncodingName("utf-8");
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setLoadWithOverviewMode(true);
Upvotes: 0