javascript - Webview 无法在 onPageFinished 加载 javascript

标签 javascript java android

我希望我的 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/

相关文章:

javascript - AngularJs:在使用 ui 路由器时实现了 IIFE

javascript - 将响应度添加到图像 slider

java - HttpURLConnection 未返回所有 header

java - 如何计算嵌套 for 循环迭代的次数?

android - 如何设置 View 透明?

javascript - 父菜单不可点击,Wordpress

javascript - OOP 事件中的 "this"

java - 尝试从 myeclipse 中的 servlet 连接到 mysql 时访问被拒绝

android - 无法从 BroadcastReceiver 调用 IntentService

android - QT + OpenSSL + 安卓