当前位置:网站首页>One of the reasons why the WebView web page cannot be opened (and some WebView problem records encountered by myself)

One of the reasons why the WebView web page cannot be opened (and some WebView problem records encountered by myself)

2022-04-23 18:44:00 KIDD-4869

prospect

WebView stay loadUrl When , There may be a problem that the web page cannot be opened , There are a lot of such problems on the Internet , But maybe after looking around, there is no answer you want , Maybe one possibility is that you usually OkHttp The request is not ignored but is configuring WebView I ignored , Please read the last article directly .

cause

I'm replacing x5WebView When I met this problem , This is the second replacement of , The first replacement did not encounter any obstacles at all , If some students encounter some configuration problems , You can go to Tencent browsing service to check the steps Portal

The problems I encountered are shown in the figure , also I tried to load Baidu home page directly , It can't be opened

 Insert picture description here

The process

Someone on the Internet said it was android:networkSecurityConfig="" There is no configuration problem , Of course not , Because these configurations have been configured before , I didn't write this project from scratch , Just take it to maintain and modify it . Follow this train of thought , I carefully compared some on the Internet WebView Configuration problem , These big differences are not bad ,domStorageEnabled = true It must have been set , None of those key configurations are missing , What could be the reason ?

In the process of replacement, I wrote a new one myself WebView Base class , I didn't look at the previous code , Just take it over and turn it over , Find yourself rewriting one less method , Replace this method x5WebView already WebView I didn't see it in the basic settings , But I thought about it , You do encounter this problem when sending network requests , Namely onReceivedSslError() Method , newly build WebViewClient This method is not rewritten ! Maybe we're doing demo I didn't rewrite it, but there's no problem , But for finished product projects , If this method is not rewritten , It should be impossible to pass .

Android Application WebView visit https SSL Certificate web page ,Google Play Always report WebView Of onReceivedSslError error (ERR_SSL_PROTOCOL_ERROR ). To avoid Google security warnings , To rewrite WebView Of onReceivedSslError Method , At this point, a pop-up box will prompt the user , Whether to ignore SSL error , Continue to visit the web page .

Baidu said .

The specific method can be seen from the old man's writing , It's still very clear Portal

What you do depends on what you do , I must be direct here SslErrorHandler.proceed 了 , There's nothing else to deal with

Treatment method

rewrite WebView Set in the WebViewClient Of onReceivedSslError() Method . Ignore ssl Certificate error , Carry on ,

		webViewClient = object : WebViewClient() {
    

                override fun onReceivedSslError(p0: WebView?, p1: SslErrorHandler?, p2: SslError?) {
    
                    p1?.proceed()
                }

                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
    
                    //  Rewriting this method indicates that the link in the web page is still in the current webview Jump in , Don't jump to the browser 
                   
                }
            }

Other problems encountered

The search box cursor is missing
After the replacement, there is a search page , When you jump in, you should pop up the keyboard , The cursor is displayed in the search box , But the ideal is always beautiful , The display is not like this . Check ,mWebView.requestFocus() Set , Re examination

	android:focusable="true"
    android:focusableInTouchMode="true"

WebView The change property has been set . It's strange , It didn't work ?
No , The keyboard pops out , But the cursor doesn't show , Probability is a focus problem , Fortunately, this problem is not very troublesome , Compared with Baidu's previous articles, there is a case to solve , Portal ! Is to put it on xml The available code for setting focus in WebView In the parent layout of , such as FrameLayout in , Run again , solve the problem .

Sliding compression problem
This problem bothered me for more than half a year , Because of this problem , I have been urged twice by the leader , The coincidence was solved , Fortunately, too web The end personnel actively cooperate .
Is to load the local static list page or the list page of some network requests , Sliding will be compressed , It's a very serious kind of , It will also appear on the real machine .
When something goes wrong , On the Internet, it is said that it is the problem of turning on hardware acceleration , But I made it clear , Didn't drive ! It is not turned on under various configurations ,app To Activity To view. I compared uncompressed WebView Set up , Two comparisons were made , In fact, there is no big problem , After copying, it will still be compressed , Then for the first time x5 after , Still compress , But it's not that good . Later, I will the static list page html Copy the content , I wrote a html, There are no styles and js, Put in... Again WebView, A magical scene appeared , No compression , Whether native or x5, All run smoothly !
And then web The style of the end has been modified , After he cancelled some style , Really no longer compress , But I can't , This style is used globally , It'll be a while and a half. It can't be cancelled ( If there are similar problems , It can make web Check first , After all WebView The only settings are those , Maybe not Native The problem of ).
This settlement is also a coincidence , Replaced the latest x5 after , I cancelled all settings related to acceleration according to the document , By default , Use a style that will cause compression , The simulator will compress slightly , But the real machine won't , I'll send the specific configuration below , It's a muddle headed way to solve this problem . summary :html Style a pot with a part on the back , Another part , It should still be with WebView of . At present, I am app Turn on hardware acceleration , however view The layer is not set , I have set this part in comparison , This is not the key to solving the problem . It's just for your reference , What causes the setting and how to solve it , I am also in a state where I can't touch my head .
To rush !

	init {
    
        //WebSettings Set up 
        settings.apply {
    
            // Set the default encoding format to “UTF-8”
            defaultTextEncodingName = "UTF-8"
            // Set up DOM Storage available 
            domStorageEnabled = true
            //js You can use 
            javaScriptEnabled = true
            // Support js Open a new window 
            javaScriptCanOpenWindowsAutomatically = true
            // Support automatic loading of pictures 
            loadsImagesAutomatically = true
            // Set the availability of database storage 
            databaseEnabled = true
            // stay File Under domain , Be able to execute arbitrary JavaScript Code , Cross domain access of the same origin policy can access private directory files and so on 
            allowFileAccess = true
            blockNetworkImage = false
            blockNetworkLoads = false
            // Set application cache availability 
            setAppCacheEnabled(true)
            // Set cache path 
            setAppCachePath(context.applicationContext.getDir("cache", Context.MODE_PRIVATE).path)
            // Cache mode : Do not use cache 
            cacheMode = WebSettings.LOAD_NO_CACHE
            // Support page scaling 
            setSupportZoom(true)
            // Zoom is controlled using the zoom in and zoom out buttons 
            builtInZoomControls = true
            // Do not display the boundary slider 
            displayZoomControls = false
            // Use browser components , It is recommended to use 
            useWideViewPort = true
            loadWithOverviewMode = true
            // Enable geolocation 
            setGeolocationEnabled(true)
            // Support Http And Https Mixed mode 
            mixedContentMode = 0
            // Set whether to allow  file url  Loaded  Js Code to read other local files ( There are risks , Non internal pages are recommended to be closed )
            setAllowFileAccessFromFileURLs(true)
            // Set whether to allow  file url  Loaded  Javascript  You can access other sources ( Include http、https Etc )( There are risks , Non internal pages are recommended to be closed )
            setAllowUniversalAccessFromFileURLs(true)
            // Adjust thread priority ( Generally, adjustment is not recommended , Default normal)
            setRenderPriority(WebSettings.RenderPriority.HIGH)
            // Cancel the vertical and horizontal sliding bars 
            isVerticalScrollBarEnabled = false
            isHorizontalScrollBarEnabled = false
            // Elastic sliding is not allowed 
            overScrollMode = View.OVER_SCROLL_NEVER
            // Hardware acceleration 
            //setLayerType(View.LAYER_TYPE_HARDWARE, null)
            webViewClient = object : WebViewClient() {
    

                override fun onReceivedSslError(p0: WebView?, p1: SslErrorHandler?, p2: SslError?) {
    
                    p1?.proceed()
                }

                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
    
                    //  Rewriting this method indicates that the link in the web page is still in the current webview Jump in , Don't jump to the browser 
                    return super.shouldOverrideUrlLoading(view, url)
                }
            }
            addJavascriptInterface(javascriptInterface, JS_OBJ_NAME)
        }
    }

版权声明
本文为[KIDD-4869]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210603464270.html