日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

HarmonyOS之常用组件WebView的使用

發布時間:2024/5/21 编程问答 82 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HarmonyOS之常用组件WebView的使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、WebView 功能

  • WebView 提供在應用中集成 Web 頁面的能力。
  • 請使用真機或模擬器運行查看 WebView 效果,預覽器不支持 WebView 顯示。
  • 只有預置 WebView 能力的真機設備才支持 WebView 功能,智能穿戴設備不支持 WebView。

二、WebView 的使用方法

  • WebView 派生于通用組件 Component,可以像普通組件一樣進行使用。
  • 在使用 WebView 時需要配置應用的網絡權限,打開“entry > src > main > config.json”,并添加如下配置:
{..."module": {..."reqPermissions": [{"name": "ohos.permission.INTERNET"}],...}}
  • 方式一:
    • 在 layout 目錄下的 xml 文件中創建 WebView:
<ohos.agp.components.webengine.WebViewohos:id="$+id:webview"ohos:height="match_parent"ohos:width="match_parent"></ohos.agp.components.webengine.WebView>
    • 在 Java 代碼中,使用 load 方法加載 Web 頁面:
WebView webView = (WebView) findComponentById(ResourceTable.Id_webview);webView.getWebConfig().setJavaScriptPermit(true); // 如果網頁需要使用JavaScript,增加此行;如何使用JavaScript下文有詳細介紹 final String url = EXAMPLE_URL; // EXAMPLE_URL由開發者自定義webView.load(url);
  • 方式二:
    • 在 Java 代碼中,通過 ComponentContainer 容器創建布局 DirectionalLayout,并在 DirectionalLayout 內添加 WebView:
DirectionalLayout dLayout = new DirectionalLayout(this);dLayout.setLayoutConfig(new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT,ComponentContainer.LayoutConfig.MATCH_PARENT));super.setUIContent(dLayout);WebView webView = new WebView(getContext());webView.setWidth(ComponentContainer.LayoutConfig.MATCH_PARENT);webView.setHeight(ComponentContainer.LayoutConfig.MATCH_PARENT);webView.getWebConfig().setJavaScriptPermit(true); // 如果網頁需要使用JavaScript,增加此行;如何使用JavaScript下文有詳細介紹dLayout.addComponent(webView);
    • 加載 Web 頁面:
final String url = EXAMPLE_URL; // EXAMPLE_URL由開發者自定義webView.load(url);

三、瀏覽網頁歷史記錄

  • 通過 getNavigator 方法獲取 Navigator 對象:
Navigator navigator = webView.getNavigator();
  • 使用 canGoBack() 或 canGoForward() 檢查是否可以向后或向前瀏覽,使用 goBack() 或 goForward() 向后或向前瀏覽:
if (navigator.canGoBack()) {navigator.goBack();}if (navigator.canGoForward()) {navigator.goForward();}

四、使用 JavaScript

  • 通過 WebConfig 啟用 JavaScript:
webView.getWebConfig().setJavaScriptPermit(true);
  • 根據實際需要選擇調用方式:
    • 注入回調對象到頁面內容,并在頁面中調用該對象:
final String jsName = "JsCallbackToApp";webView.addJsCallback(jsName, new JsCallback() {@Overridepublic String onCallback(String msg) {// 增加自定義處理return "jsResult";}});
    • 在頁面內通過 JavaScript 代碼調用注入對象:
function callToApp() {if (window.JsCallbackToApp && window.JsCallbackToApp.call) {var result = JsCallbackToApp.call("message from web");}}
    • 在應用內調用頁面內的 JavaScript 方法:
webView.executeJs("javascript:callFuncInWeb()", new AsyncCallback<String>() {@Overridepublic void onReceive(String msg) {// 在此確認返回結果}});

五、觀測 Web 狀態

  • 通過 setWebAgent 方法設置自定義 WebAgent 對象,以觀測頁面狀態變更等事件:
webView.setWebAgent(new WebAgent() {@Overridepublic void onLoadingPage(WebView webview, String url, PixelMap favicon) {super.onLoadingPage(webview, url, favicon);// 頁面開始加載時自定義處理}@Overridepublic void onPageLoaded(WebView webview, String url) {super.onPageLoaded(webview, url);// 頁面加載結束后自定義處理}@Overridepublic void onLoadingContent(WebView webview, String url) {super.onLoadingContent(webview, url);// 加載資源時自定義處理}@Overridepublic void onError(WebView webview, ResourceRequest request, ResourceError error) {super.onError(webview, request, error);// 發生錯誤時自定義處理}});

六、觀測瀏覽事件

  • 通過 setBrowserAgent 方法設置自定義 BrowserAgent 對象,以觀測 JavaScript 事件及通知等:
webView.setBrowserAgent(new BrowserAgent(this) {@Overridepublic void onTitleUpdated(WebView webview, String title) {super.onTitleUpdated(webview, title);// 標題變更時自定義處理}@Overridepublic void onProgressUpdated(WebView webview, int newProgress) {super.onProgressUpdated(webview, newProgress);// 加載進度變更時自定義處理}});

七、定制網址加載行為

  • 當 Web 頁面進行鏈接跳轉時,WebView 默認會打開目標網址,通過以下方式可以定制該行為。
  • 自定義 WebAgent 對象:
private class ExampleWebAgent extends WebAgent {public static final String EXAMPLE_URL = "...";@Overridepublic boolean isNeedLoadUrl(WebView webview, ResourceRequest request) { if (request == null || request.getRequestUrl() == null) {return false;}Uri uri = request.getRequestUrl();// EXAMPLE_URL由開發者自定義if (uri.getDecodedHost().equals(EXAMPLE_URL)) {// 增加開發者自定義邏輯return false;} else {return super.isNeedLoadUrl(webview, request);}}}
  • 設置自定義 WebAgent 至 WebView:
webView.setWebAgent(new ExampleWebAgent());

八、加載資源文件或本地文件

  • 出于安全考慮,WebView 不支持直接通過 File 協議加載資源文件或本地文件。
  • 如應用需實現相關業務,可參考如下方式實現。
① 通過 processResourceRequest 方法訪問文件
  • 通過 setWebAgent 方法設置自定義 WebAgent 對象,覆寫 processResourceRequest 方法。
webView.setWebAgent(new WebAgent() {@Overridepublic 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);}});
  • 在 resources 目錄下的 rawfile 路徑下創建"example.html"資源文件,以及在本機設備內創建"example.html"本地文件。
  • 加載資源文件或本地文件:
// 加載資源文件 resources/rawfile/example.htmlwebView.load("https://example.com/rawfile/example.html");// 加載本地文件 /data/data/com.example.dataability/files/example.htmlwebView.load("https://example.com/local/example.html");
② 通過 Data Ability 訪問文件
  • 創建 Java 文件 Data Ability:
public class ExampleDataAbility extends Ability {private static final String PLACEHOLDER_RAW_FILE = "/rawfile/";private static final String PLACEHOLDER_LOCAL_FILE = "/local/";private static final String ENTRY_PATH_PREFIX = "entry/resources";@Overridepublic RawFileDescriptor openRawFile(Uri uri, String mode) throws FileNotFoundException {final int splitChar = '/';if (uri == null) {throw new FileNotFoundException("Invalid Uri");}// path will be like /com.example.dataability/rawfile/example.htmlString path = uri.getEncodedPath();final int splitIndex = path.indexOf(splitChar, 1);if (splitIndex < 0) {throw new FileNotFoundException("Invalid Uri " + uri);}String targetPath = path.substring(splitIndex);if (targetPath.startsWith(PLACEHOLDER_RAW_FILE)) {// 根據自定義規則訪問資源文件try {return getResourceManager().getRawFileEntry(ENTRY_PATH_PREFIX + targetPath).openRawFileDescriptor();} catch (IOException e) {throw new FileNotFoundException("Not found support raw file at " + uri);}} else if (targetPath.startsWith(PLACEHOLDER_LOCAL_FILE)) {// 根據自定義規則訪問本地文件File file = new File(getContext().getFilesDir(), targetPath.replace(PLACEHOLDER_LOCAL_FILE, ""));if (!file.exists()) {throw new FileNotFoundException("Not found support local file at " + uri);}return getRawFileDescriptor(file, uri);} else {throw new FileNotFoundException("Not found support file at " + uri);}}private RawFileDescriptor getRawFileDescriptor(File file, Uri uri) throws FileNotFoundException {try {final FileDescriptor fileDescriptor = new FileInputStream(file).getFD();return new RawFileDescriptor() {@Overridepublic FileDescriptor getFileDescriptor() {return fileDescriptor;}@Overridepublic long getFileSize() {return -1;}@Overridepublic long getStartPosition() {return 0;}@Overridepublic void close() throws IOException {}};} catch (IOException e) {throw new FileNotFoundException("Not found support local file at " + uri);}}}
  • 在 config.json 中注冊 Data Ability,以及在 resources/base/profile 目錄新增 path.xml:
{"name": "com.example.webview.ExampleDataAbility","type": "data","uri": "dataability://com.example.dataability","metaData": {"customizeData": [{"name": "com.example.provider","extra": "$profile:path"}]}} <paths><root-path name="root" path="/" /></paths>
  • 在 resources 目錄下的 rawfile 路徑下創建"example.html"資源文件,以及在本機設備內創建"example.html"本地文件。
  • 配置支持訪問 Data Ability 資源:
webConfig.setDataAbilityPermit(true);
  • 通過 dataability 協議加載資源文件或本地文件:
// 加載資源文件 resources/rawfile/example.htmlwebView.load("dataability://com.example.dataability/rawfile/example.html");// 加載本地文件 /data/data/com.example.dataability/files/example.htmlwebView.load("dataability://com.example.dataability/local/example.html");

總結

以上是生活随笔為你收集整理的HarmonyOS之常用组件WebView的使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。