我希望我的 webview 在页面加载后插入某种 javascript。但是,我添加的 javascript 从未执行过:( 我能做什么?
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
"})()");
}
});
即使我注释掉除 alert
行之外的所有脚本,仍然没有任何反应。
最佳答案
你必须在应用程序端使用这样的
mWebView .addJavascriptInterface(new WebAppInterface(this), "Android");
并且必须在实际触发此方法的 php 端实现方法
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();
}
}
在 PHP 端实现这样
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
如需完整引用,您可以浏览 this link
每当您点击 webView
上的按钮时,您都会收到一条消息
关于javascript - Webview 无法在 onPageFinished 加载 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54740203/