当前位置:   article > 正文

【Harmony OS】WebView调用JS并获取执行结果_鸿蒙webview 导入js

鸿蒙webview 导入js

WebView提供了在应用中集成Web页面的能力。在日常的开发中也会经常用到。
WebView派生于通用组件Component,可以像普通组件一样进行使用。
今天我们就介绍如何在应用内调用页面内的JavaScript方法。
参考网址:
文档中心
代码实现:
html代码如下:

  1. <!DOCTYPE html>
  2. <html>
  3. <meta charset="UTF-8">
  4. <title>本地html</title>
  5. <body>
  6. <br>
  7. <h1 id="helloName">这是一个本地HTML页面</h1>
  8. <br>
  9. <button
  10. id="button"
  11. style="background-color:#70DBDB;height:30px;">调用Java方法
  12. </button>
  13. <input style="background-color:#70DBDB;height:30px; " >
  14. <script type="text/javascript">
  15. // 应用调用Web页面
  16. function callJS(message) {
  17. alert(message);
  18. return '123'
  19. }
  20. function sendData() {
  21. if (window.JsCallJava && window.JsCallJava.call) {
  22. // Web页面调用应用
  23. var rst = window.JsCallJava.call("这个是来自本地Web页面的消息");
  24. } else {
  25. alert('发送消息给WebviewSlice失败');
  26. }
  27. }
  28. function getCookie(name) {
  29. var prefix = name + "="
  30. var start = document.cookie.indexOf(prefix)
  31. if (start == -1) {
  32. return null;
  33. }
  34. var end = document.cookie.indexOf(";", start + prefix.length)
  35. if (end == -1) {
  36. end = document.cookie.length;
  37. }
  38. var value = document.cookie.substring(start + prefix.length, end)
  39. return unescape(value);
  40. }
  41. </script>
  42. </body>
  43. </html>

xml代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <DirectionalLayout
  3. xmlns:ohos="http://schemas.huawei.com/res/ohos"
  4. ohos:height="match_parent"
  5. ohos:width="match_parent"
  6. ohos:orientation="vertical">
  7. <Image
  8. ohos:id="$+id:myImage"
  9. ohos:height="100vp"
  10. ohos:width="100vp"
  11. ohos:image_src="$media:icon"/>
  12. <ohos.agp.components.webengine.WebView
  13. ohos:id="$+id:webview"
  14. ohos:height="0vp"
  15. ohos:weight="1"
  16. ohos:width="match_parent">
  17. </ohos.agp.components.webengine.WebView>
  18. </DirectionalLayout>

Java代码如下:

  1. package com.example.newwebview.slice;
  2. import com.example.newwebview.ResourceTable;
  3. import com.example.newwebview.utils.HiLogUtils;
  4. import ohos.aafwk.ability.AbilitySlice;
  5. import ohos.aafwk.content.Intent;
  6. import ohos.agp.components.Component;
  7. import ohos.agp.components.webengine.*;
  8. import ohos.agp.render.BlendMode;
  9. import ohos.agp.render.Paint;
  10. import ohos.agp.utils.TextTool;
  11. import ohos.agp.window.service.WindowManager;
  12. import ohos.global.resource.Resource;
  13. import ohos.hiviewdfx.HiLog;
  14. import ohos.media.image.ImagePacker;
  15. import ohos.media.image.PixelMap;
  16. import ohos.media.image.common.PixelFormat;
  17. import ohos.media.image.common.Size;
  18. import ohos.utils.net.Uri;
  19. import java.io.*;
  20. import java.net.*;
  21. public class WebViewAbility extends AbilitySlice {
  22. private static final String URL_LOCAL = "dataability://example.com/rawfile/example.html";
  23. @Override
  24. protected void onStart(Intent intent) {
  25. super.onStart(intent);
  26. setUIContent(ResourceTable.Layout_new_web_view);
  27. getWindow().setInputPanelDisplayType(WindowManager.LayoutConfig.INPUT_ADJUST_PAN);
  28. WebView webview= (WebView) findComponentById(ResourceTable.Id_webview);
  29. // 是否支持Javascript,默认值false
  30. webview.getWebConfig().setJavaScriptPermit(true);
  31. webview.setWebAgent(new WebAgent() {
  32. @Override
  33. public ResourceResponse processResourceRequest(WebView webView, ResourceRequest request) {
  34. final String authority = "example.com";
  35. final String rawFile = "/rawfile/";
  36. final String local = "/local/";
  37. Uri requestUri = request.getRequestUrl();
  38. if (authority.equals(requestUri.getDecodedAuthority())) {
  39. String path = requestUri.getDecodedPath();
  40. if (TextTool.isNullOrEmpty(path)) {
  41. return super.processResourceRequest(webView, request);
  42. }
  43. if (path.startsWith(rawFile)) {
  44. // 根据自定义规则访问资源文件
  45. String rawFilePath = "entry/resources/rawfile/" + path.replace(rawFile, "");
  46. String mimeType = URLConnection.guessContentTypeFromName(rawFilePath);
  47. try {
  48. Resource resource = getResourceManager().getRawFileEntry(rawFilePath).openRawFile();
  49. ResourceResponse response = new ResourceResponse(mimeType, resource, null);
  50. return response;
  51. } catch (IOException e) {
  52. // HiLog.info(TAG, "open raw file failed");
  53. }
  54. }
  55. if (path.startsWith(local)) {
  56. // 根据自定义规则访问本地文件
  57. String localFile = getContext().getFilesDir() + path.replace(local, "/");
  58. // HiLog.info(TAG, "open local file " + localFile);
  59. File file = new File(localFile);
  60. if (!file.exists()) {
  61. // HiLog.info(TAG, "file not exists");
  62. return super.processResourceRequest(webView, request);
  63. }
  64. String mimeType = URLConnection.guessContentTypeFromName(localFile);
  65. try {
  66. InputStream inputStream = new FileInputStream(file);
  67. ResourceResponse response = new ResourceResponse(mimeType, inputStream, null);
  68. return response;
  69. } catch (IOException e) {
  70. // HiLog.info(TAG, "open local file failed");
  71. }
  72. }
  73. }
  74. return super.processResourceRequest(webView, request);
  75. }
  76. });
  77. webview.setBrowserAgent(new BrowserAgent(WebViewAbility.this){
  78. @Override
  79. public boolean onJsMessageShow(WebView webView, String url, String message, boolean isAlert, JsMessageResult result) {
  80. HiLogUtils.PrintLog(url);
  81. return false;
  82. }
  83. });
  84. webview.load(URL_LOCAL);
  85. findComponentById(ResourceTable.Id_myImage).setClickedListener(new Component.ClickedListener() {
  86. @Override
  87. public void onClick(Component component) {
  88. webview.executeJs("callJS('这是来自JavaSlice的消息')", msg -> {
  89. // 在这里处理Java调用Js的方法的返回值
  90. HiLogUtils.PrintLog("msg====>>>"+msg);
  91. });
  92. }
  93. });
  94. }
  95. private void setWindowBgToAdaptWebView() {
  96. final String backgroundFileName = "_bg.jpg";
  97. File file = new File(getContext().getFilesDir(), backgroundFileName);
  98. if (file.exists()) {
  99. getWindow().setBackground(file.getPath());
  100. return;
  101. }
  102. PixelMap pixelMap = createBgPixelMap();
  103. if (pixelMap == null) {
  104. return;
  105. }
  106. ImagePacker imagePacker = ImagePacker.create();
  107. try (OutputStream outputStream = new FileOutputStream(file)) {
  108. ImagePacker.PackingOptions options = new ImagePacker.PackingOptions();
  109. if (!imagePacker.initializePacking(outputStream, options)) {
  110. return;
  111. }
  112. if (!imagePacker.addImage(pixelMap)) {
  113. return;
  114. }
  115. if (imagePacker.finalizePacking() < 0) {
  116. return;
  117. }
  118. } catch (IOException e) {
  119. e.printStackTrace();
  120. } finally {
  121. imagePacker.release();
  122. }
  123. }
  124. private PixelMap createBgPixelMap() {
  125. final int length = 10;
  126. PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
  127. initializationOptions.size = new Size(length, length);
  128. initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
  129. initializationOptions.editable = true;
  130. int[] defaultColors = new int[length * length];
  131. return PixelMap.create(defaultColors, initializationOptions);
  132. }
  133. }

运行效果如下:

cke_10849.png

注:如果执行的js是不能编辑的页面,可以参考:
Android WebView 调用JS方法获取返回值_Luckie stone的博客-CSDN博客_js调用android的方法返回值

 

 欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号