繁体   English   中英

如何通过 JavaScript 在 android webview 中监听页面 beforeunload 或 unload 事件

[英]How to listen the page beforeunload or unload event in android webview by JavaScript

我使用 WebView 加载我的页面如下:

<html>
    <head>

    </head>
    <body>
        <h1>first page</h1>
        <script>
            (function(){
                function log(e){
                    console.log("Page is going to unload:"+e);
                }
                window.addEventListener('beforeunload',log);
                window.addEventListener('unload',log);
            })()
        </script>
    </body>
</html>

此页面在 Chrome 或其他 PC 浏览器中运行良好。

这是活动中的代码:

public class MainActivity extends AppCompatActivity {
    WebView web;
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        web = findViewById(R.id.web);
        web.setWebContentsDebuggingEnabled(true);
        WebSettings webSettings = web.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);

        web.loadUrl("http://192.168.0.103:5000/WebContent/");

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        Log.i("SSSS","acitvity destroyed");
        super.onDestroy();
        ConstraintLayout layout = this.findViewById(R.id.rootView);
        layout.removeView(web);
        web.destroy();
        web = null;
    }

}

当离开包含 WebView 的活动时,我无法捕获有关页面卸载事件的任何日志,有什么问题吗?

我没有对此进行测试,但根据您需要覆盖WebChromeClient::onConsoleMessage并使用WebView::setWebChromeClient 的文档

这是因为您要在onDestroy中删除视图和 Webview

@Override
    protected void onDestroy() {
        Log.i("SSSS","acitvity destroyed");
        super.onDestroy();
        ConstraintLayout layout = this.findViewById(R.id.rootView);
        layout.removeView(web);   <----- This linse
        web.destroy(); <------ Forcing webview to destroy and next explicitly set null
        web = null;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM