Android WebView loads web pages, pictures and other elements whose width and size are not compatible with the width of the mobile phone screen

Whether it is an Android mobile phone or an iOS mobile phone, when using WebView to load some webpages that are not specially adapted for the mobile phone screen, the width of the label elements such as pictures in the webpage will be inconsistent with the width of the mobile phone screen, as shown in the following figure


The above situation occurs because the size of the dom element in the web page is not adapted to the mobile web page, and some elements have a fixed width.

There are many solutions:

  1. Front-end personnel adapt the web page to the mobile terminal (advantages: the most standardized approach Disadvantages: some projects that are no longer maintained are not adapted by front-end personnel)
  2. Mobile developers can modify it by themselves through JS injection (advantage: without the support of front-end personnel, this can be done reluctantly. Disadvantage: if the element changes, Native needs to modify various JS functions)

Now let's focus on the second method:

     First of all, on the two platforms of Android and iOS, WebView can interact with Native, write JS functions in Native and inject it into html, or call Native functions on web pages.

     Here I will briefly talk about injecting JS into html to change the size of the corresponding element, as well as the font, etc. Both Android and iOS have WebView, which can monitor the process of monitoring the loading of web pages. In Android, WebViewClient is used to monitor web pages. In the loading process, we generally need to inject JS after all the resources of the web page are loaded, that is, in the onPageFinish method. Not much nonsense, just look at the code:

package com.example.webviewdemo;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "WebView";

    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webView);
        initWebSettings();

        webView.loadUrl("http://www.ah12377.cn/newsDetail/151");

        //Listen to see if the WebView has finished loading the webpage
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.d(TAG,"onPageFinished");
                loadJS();
            }
        });


    }

    private void loadJS(){
        webView.loadUrl("javascript:(function(){"
                //Set the margin and padding in the DIV element to zero to prevent gaps on the left and right of the web page
                + " var divs = document.getElementsByTagName(\"div\");"
                + " for(var j=0;j<divs.length;j++){"
                + "   divs[j].style.margin=\"0px\";"
                + "   divs[j].style.padding=\"0px\";"
                + "   divs[j].style.width=document.body.clientWidth-10;"
                + " }"

                + " var imgs = document.getElementsByTagName(\"img\"); "
                + "   for(var i=0;i<imgs.length;i++)  "
                + "       {"
                       //Filter out the GIF image to prevent the GIF from being distorted after excessive enlargement
                + "    var vkeyWords=/.gif$/;"
                + "        if(!vkeyWords.test(imgs[i].src)){"
                + "         var hRatio="+getScreenWidthPX()+"/objs[i].width;"
                + "objs[i].height= objs[i].height*hRatio;"//Set the height of the picture by scaling
                + " objs[i].width="+getScreenWidthPX()+";"//Set the width of the picture
                + "        }"
                +    "}"
                +   "})()");
    }



    /**
     * WebView Setting
     */
    private void initWebSettings(){
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

    }

    /**
     * Get the width of the screen (unit: pixel PX)
     * @return
     */
    private int getScreenWidthPX(){
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        if (wm != null && wm.getDefaultDisplay() != null){
           wm.getDefaultDisplay().getMetrics(dm);
           return px2dip(dm.widthPixels);
        }else {
            return 0;
        }
    }

    /**
     * Pixel to DP
     * @param pxValue
     * @return
     */
    public  int px2dip(float pxValue) {
        float scale = this.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}

The code is very simple, and the rendering is as follows. From the above code, we can know that we can modify any element of html through JS, and we can also remove or hide elements in html, etc. Of course, we also need to understand the development of JS and html in order to improve Good start, of course, it is also important to use the debugging panel of the Chrome browser for this process

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325775380&siteId=291194637