当前位置:   article > 正文

鸿蒙开发(17)---WebView组件_鸿蒙 webview

鸿蒙 webview

WebView组件

在实际的App开发中,我们往往还会直接跳转到网页。比如微信人家给你发了一个链接,默认也是在App之内打开的。

当然,很多公司的App就只使用一个WebView作为整体框架,比如我们常用的读书App:掌阅等。这样开发的好处是,只要使用少量的代码即可完成交互。

所以,今天我们将来介绍鸿蒙App的WebView组件的使用方式。

基本用法

首先,与前面讲解的其他组件一样,这里通过XML布局文件进行操作。示例代码如下:

<ohos.agp.components.webengine.WebView
    ohos:id="$+id:ability_main_webview"
    ohos:height="match_parent"
    ohos:width="match_parent"/>
  • 1
  • 2
  • 3
  • 4

需要注意的是,博主这里输入的是ohos.agp.components.webengine.WebView,你直接输入WebView也是有提示的。

不过,WebView与ohos.agp.components.webengine.WebView并不等价,这可能是鸿蒙的一个漏洞,直接输入WebView并不能使用这个组件。

接下来,就需要加载我们的网页进行显示,代码如下所示:

public class MainAbilitySlice extends AbilitySlice {
    private WebView webView;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        this.webView=(WebView)findComponentById(ResourceTable.Id_ability_main_webview);
        this.webView.load("https://www.baidu.com");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

很简单,我们使用load()函数进行网页的加载。不过,在主界面,直接这么加载是不会显示任何东西的。

防止WebView跳转到浏览器

这是因为,鸿蒙默认的WebView组件是直接跳转到浏览器的,而你在主页这么做,那连显示都不必,何必安装App呢?

所以,我们需要禁止WebView跳转到浏览器,它才可能在主页显示这个组件。而它的setWebAgent()方法就是防止跳转浏览器的。示例如下:

public class MainAbilitySlice extends AbilitySlice {
    private WebView webView;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        this.webView=(WebView)findComponentById(ResourceTable.Id_ability_main_webview);
        this.webView.setWebAgent(new WebAgent(){
            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                return super.isNeedLoadUrl(webView, request);
            }
        });
        this.webView.load("https://www.baidu.com/");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

这里就是默认设置一下WebAgent,并覆写isNeedLoadUrl方法,当然什么都不动就行。isNeedLoadUrl主要检查是否基于当前WebView请求加载。

运行之后,效果如下:

运行效果

使用JavaScript

鸿蒙的WebView组件默认是不支持JavaScript,需要进行设置。通过如下代码,即可完成JavaScript交互。

webView.getWebConfig().setJavaScriptPermit(true);
  • 1

网页调用App方法

要完成网页与App的交互,必然涉及到两者的数据交互以及方法的调用。比如,这里我们通过网页让App弹出网页指定的内容。示例如下:

final String jsName = "JsCallbackToApp";
    webView.addJsCallback(jsName, new JsCallback() {
        @Override
        public String onCallback(String msg) {
            new ToastDialog(getContext())
                .setText(msg)
                .show();
            return "jsResult";
        }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在网页中,我们需要通过JsCallbackToApp.call传递参数调用。代码如下:

function myClick() {
    var result = JsCallbackToApp.call("我是网页传递给App的数据");
}
  • 1
  • 2
  • 3

App调用网页方法

同样的,我们有时候也要将App的处理结果传递给网页进行处理。这里我们通过executeJs()方法进行调用,示例如下:

webView.executeJs("javascript:aAddb(5,5)", new AsyncCallback<String>() {
    @Override
    public void onReceive(String msg) {
        new ToastDialog(getContext())
            .setText("a+b="+msg)
            .show();
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

同时,需要定义与executeJs第1个方法参数同名的方法,代码如下:

function aAddb(a, b) {
    return a + b;
}
  • 1
  • 2
  • 3

资源文件中引用网页

在鸿蒙App的项目中,有一个rawfile文件夹,是专门用于放置我们非应用配置的额外文件的。比如,这里我们放置html文件,如下图所示:
exampleHTML
通过WebAgent的processResourceRequest()方法,我们可以直接按自己定义的文件规则加载html文件。代码如下:

public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
    	this.webView.setWebAgent(new WebAgent(){
            @Override
            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
                return super.isNeedLoadUrl(webView, request);
            }

            @Override
            public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
                final String authority = "example.com";
                final String rawFile = "/rawfile/";
                final String local = "/local/";
                Uri requestUri = request.getRequestUrl();
                if (authority.equals(requestUri.getDecodedAuthority())) {
                    String path = requestUri.getDecodedPath();
                    if (TextTool.isNullOrEmpty(path)) {
                        return super.processResourceRequest(webView, request);
                    }
                    if (path.startsWith(rawFile)) {
                        // 根据自定义规则访问资源文件
                        String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
                        String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
                        try {
                            Resource resource = getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
                            ResourceResponse response = new ResourceResponse(mimeType, resource, null);
                            return response;
                        } catch (IOException e) {
                            HiLog.info(TAG, "open raw file failed");
                        }
                    }
                    if (path.startsWith(local)) {
                        // 根据自定义规则访问本地文件
                        String localFile = getContext().getFilesDir() + path.replace(local, "/");
                        HiLog.info(TAG, "open local file " + localFile);
                        File file = new File(localFile);
                        if (!file.exists()) {
                            HiLog.info(TAG, "file not exists");
                            return super.processResourceRequest(webView, request);
                        }
                        String mimeType = URLConnection.guessContentTypeFromName(localFile);
                        try {
                            InputStream inputStream = new FileInputStream(file);
                            ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
                            return response;
                        } catch (IOException e) {
                            HiLog.info(TAG, "open local file failed");
                        }
                    }
                }
                return super.processResourceRequest(webView, request);
            }
        });
        this.webView.getWebConfig().setJavaScriptPermit(true);
        this.webView.load("https://example.com/rawfile/example.html");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

processResourceRequest()方法是在请求资源时调用。

而网页的源代码如下所示:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>title</title>
        <script type="text/javascript">
        function myClick() {
             var result = JsCallbackToApp.call("我是网页传递给App的数据");
        }
        function aAddb(a, b) {
            return a + b;
        }
        </script>
    </head>
    <body>
        <input
                type="button"
                onclick="myClick()"
                value="弹出鸿蒙ToastDialog"/>
    </body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

鸿蒙里面还有一个提示组件ToastDialog,但是这是一个简单的组件,在我们WebView进行交互的时候已经介绍过了,单独一篇博文太多,就不在赘述。

运行之后,效果如下:

最终效果
本文源代码:https://github.com/liyuanjinglyj/JavaCardDemo

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/307014
推荐阅读
相关标签
  

闽ICP备14008679号