鴻蒙應(yīng)用開發(fā)-webview 組件(使用和調(diào)試)

目錄

1.WebView 組件介紹

HarmonyOS中的Web組件是一種基于Web技術(shù)的組件,可以在HarmonyOS應(yīng)用程序中嵌入Web內(nèi)容。通過使用Web組件,開發(fā)人員可以將Web頁面或應(yīng)用程序嵌入到HarmonyOS應(yīng)用程序中,實現(xiàn)更豐富的用戶界面和功能。

Web組件提供了一系列的API和工具,開發(fā)人員可以使用這些API和工具來控制和操作內(nèi)嵌的Web頁面。例如,開發(fā)人員可以使用JavaScriptCSS來操作和樣式化Web頁面的元素,還可以使用HTML5的各種功能來實現(xiàn)各種交互和媒體功能。

Web組件還支持與HarmonyOS應(yīng)用程序的其他部分進(jìn)行通信和交互。開發(fā)人員可以使用JavaScriptHarmonyOS的API來實現(xiàn)應(yīng)用程序的功能,例如訪問設(shè)備的傳感器、調(diào)用系統(tǒng)的功能等。此外,Web組件還可以通過與應(yīng)用程序的其他組件進(jìn)行交互來實現(xiàn)更復(fù)雜的功能,例如在應(yīng)用程序的其他組件中顯示Web頁面的內(nèi)容、發(fā)送和接收消息等。

功能 描述
頁面加載 Web組件提供基礎(chǔ)的前端頁面加載能力,包括加載網(wǎng)絡(luò)頁面、本地頁面、Html格式文本數(shù)據(jù)。
頁面交互 Web組件提供豐富的頁面交互方式,包括設(shè)置前端頁面深色模式,新窗口中加載頁面,位置權(quán)限管理,Cookie管理,應(yīng)用側(cè)使用前端頁面JavaScript等能力。
頁面調(diào)試 Web組件支持使用Devtools工具調(diào)試前端頁面。

2.使用Web組件加載頁面

  • 2.1 加載網(wǎng)絡(luò)頁面

1、權(quán)限配置

"requestPermissions": [
  {
    "name": "ohos.permission.INTERNET" // 使用網(wǎng)絡(luò)權(quán)限
  }
]

2、加載網(wǎng)頁

import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  build() {
    Column() {
      Button('加載首頁')
        .onClick(() => {
          try {
            // 點擊按鈕時,通過loadUrl,跳轉(zhuǎn)到www.example1.com
            this.controller.loadUrl('blog.csdn.net/aa2528877987');
          } catch (error) {
            console.error(`ErrorCode: ${error.code},  Message: ${error.message}`);
          }
        })
      // 組件創(chuàng)建時,加載www.example.com
      Web({ src: 'www.baidu.com', controller: this.controller})
    }
  }
}
  • 2.2 加載本地頁面
    1、ets 文件
// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  webviewController: web_webview.WebviewController = new web_webview.WebviewController();

  build() {
    Column() {
      Button('loadUrl')
        .onClick(() => {
          try {
            // 點擊按鈕時,通過loadUrl,跳轉(zhuǎn)到local1.html
            this.webviewController.loadUrl($rawfile("local1.html"));
          } catch (error) {
            console.error(`ErrorCode: ${error.code},  Message: ${error.message}`);
          }
        })
      // 組件創(chuàng)建時,通過$rawfile加載本地文件local.html
      Web({ src: $rawfile("local.html"), controller: this.webviewController })
    }
  }
}

2、本地頁面

<!-- local.html -->
<!DOCTYPE html>
<html>
  <body>
    <p>Hello World</p>
  </body>
</html>
  • 2.3 加載HTML格式的文本數(shù)據(jù)
// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController();

  build() {
    Column() {
      Button('loadData')
        .onClick(() => {
          try {
            // 點擊按鈕時,通過loadData,加載HTML格式的文本數(shù)據(jù)
            this.controller.loadData(
              "<html><body bgcolor="white">Source:<pre>source</pre></body></html>",
              "text/html",
              "UTF-8"
            );
          } catch (error) {
            console.error(`ErrorCode: ${error.code},  Message: ${error.message}`);
          }
        })
      // 組件創(chuàng)建時,加載www.example.com
      Web({ src: 'www.example.com', controller: this.controller })
    }
  }
}

3.設(shè)置基本屬性和事件

3.1 設(shè)置深色模式

通過darkMode()接口可以配置不同的深色模式。

  • WebDarkMode.Off模式表示關(guān)閉深色模式。
  • WebDarkMode.On表示開啟深色模式,且深色模式跟隨前端頁面。
  • WebDarkMode.Auto表示開啟深色模式,且深色模式跟隨系統(tǒng)。
  • forceDarkAccess()接口可將前端頁面強(qiáng)制配置深色模式,且深色模式不跟隨前端頁面和系統(tǒng)。配置該模式時候,需要配置成WebDarkMode.On
// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController();
  @State mode: WebDarkMode = WebDarkMode.On;
  @State access: boolean = true;
  build() {
    Column() {
      Web({ src: 'www.example.com', controller: this.controller })
        .darkMode(this.mode)
        .forceDarkAccess(this.access)
    }
  }
}

3.2 上傳文件

HarmonyOSWeb組件的onShowFileSelector()方法用于顯示文件選擇器,讓用戶選擇文件。它可以用于在應(yīng)用中上傳文件或選擇本地文件等操作。

// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  build() {
    Column() {
      // 加載本地local.html頁面
      Web({ src: $rawfile('local.html'), controller: this.controller })
        .onShowFileSelector((event) => {
            // 開發(fā)者設(shè)置要上傳的文件路徑
           let fileList: Array<string> = [
              'xxx/test.png',
           ]
           event.result.handleFileList(fileList)
           return true;
        })
    }
  }
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Document</title>
</head>

<body>
// 點擊文件上傳按鈕
<input type="file" value="file"></br>
</body>
</html>
image.png

3.3 在新窗口中打開頁面

開發(fā)者可以使用multiWindowAccess()接口來設(shè)置網(wǎng)頁是否可以在新窗口中打開。通過調(diào)用此接口并傳入相應(yīng)的參數(shù),可以控制網(wǎng)頁是否允許使用新窗口。
當(dāng)網(wǎng)頁請求在新窗口中打開時,應(yīng)用將收到Web組件的新窗口事件,可以通過onWindowNew()接口來處理此事件。在此接口中,開發(fā)者可以根據(jù)需要創(chuàng)建新的窗口來處理Web組件的窗口請求。

// xxx.ets
import web_webview from '@ohos.web.webview'

//在同一page頁有兩個web組件。在WebComponent新開窗口時,會跳轉(zhuǎn)到NewWebViewComp。
@CustomDialog
struct NewWebViewComp {
controller?: CustomDialogController
webviewController1: web_webview.WebviewController = new web_webview.WebviewController()
build() {
    Column() {
      Web({ src: "", controller: this.webviewController1 })
        .javaScriptAccess(true)
        .multiWindowAccess(false)
        .onWindowExit(()=> {
          console.info("NewWebViewComp onWindowExit")
          if (this.controller) {
            this.controller.close()
          }
        })
      }
  }
}

@Entry
@Component
struct WebComponent {
    controller: web_webview.WebviewController = new web_webview.WebviewController()
    dialogController: CustomDialogController | null = null
    build() {
      Column() {
        Web({ src:$rawfile("window.html"), controller: this.controller })
          .javaScriptAccess(true)
         //需要使能multiWindowAccess
          .multiWindowAccess(true)
          .allowWindowOpenMethod(true)
          .onWindowNew((event) => {
          if (this.dialogController) {
            this.dialogController.close()
          }
          let popController:web_webview.WebviewController = new web_webview.WebviewController()
          this.dialogController = new CustomDialogController({
            builder: NewWebViewComp({webviewController1: popController})
          })
          this.dialogController.open()
          //將新窗口對應(yīng)WebviewController返回給Web內(nèi)核。
          //如果不需要打開新窗口請調(diào)用event.handler.setWebController接口設(shè)置成null。
          //若不調(diào)用event.handler.setWebController接口,會造成render進(jìn)程阻塞。
          event.handler.setWebController(popController)
        })
    }
  }
}
 <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>WindowEvent</title>
</head>
<body>
<input type="button" value="新窗口中打開網(wǎng)頁" onclick="OpenNewWindow()">
<script type="text/javascript">
    function OpenNewWindow()
    {
        let openedWindow = window.open("about:blank", "", "location=no,status=no,scrollvars=no");
        openedWindow.document.write("<p>這是我的窗口</p>");
        openedWindow.focus();
    }
</script>
</body>
</html>

3.4 管理位置權(quán)限

對于某個網(wǎng)站進(jìn)行位置權(quán)限管理的過程中,開發(fā)者可以通過onGeolocationShow()接口來向用戶請求位置權(quán)限。該接口會觸發(fā)一個位置權(quán)限請求對話框,用戶可以選擇是否授權(quán)該網(wǎng)站獲取設(shè)備的位置信息。
Web組件會根據(jù)用戶的選擇,將權(quán)限授予或拒絕。如果權(quán)限被授予,前端頁面將能夠獲取設(shè)備的位置信息。如果權(quán)限被拒絕,前端頁面將無法獲取設(shè)備的位置信息。
在進(jìn)行位置權(quán)限請求之前,開發(fā)者需要在應(yīng)用的配置文件中添加ohos.permission.LOCATION權(quán)限,以確保應(yīng)用有權(quán)限獲取設(shè)備的位置信息。

<!DOCTYPE html>
<html>
<body>
<p id="locationInfo">位置信息</p>
<button onclick="getLocation()">獲取位置</button>
<script>
var locationInfo=document.getElementById("locationInfo");
function getLocation(){
  if (navigator.geolocation) {
    <!-- 前端頁面訪問設(shè)備地理位置 -->
    navigator.geolocation.getCurrentPosition(showPosition);
  }
}
function showPosition(position){
  locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
// xxx.ets
import web_webview from '@ohos.web.webview';

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController();
  build() {
    Column() {
      Web({ src:$rawfile('getLocation.html'), controller:this.controller })
        .geolocationAccess(true)
        .onGeolocationShow((event) => {  // 地理位置權(quán)限申請通知
          AlertDialog.show({
            title: '位置權(quán)限請求',
            message: '是否允許獲取位置信息',
            primaryButton: {
              value: 'cancel',
              action: () => {
                event.geolocation.invoke(event.origin, false, false);   // 不允許此站點地理位置權(quán)限請求
              }
            },
            secondaryButton: {
              value: 'ok',
              action: () => {
                event.geolocation.invoke(event.origin, true, false);    // 允許此站點地理位置權(quán)限請求
              }
            },
            cancel: () => {
              event.geolocation.invoke(event.origin, false, false);   // 不允許此站點地理位置權(quán)限請求
            }
          })
        })
    }
  }
}

4.請求響應(yīng)

4.1 前端代碼
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>example</title>
</head>
<body>
<!-- 頁面資源請求 -->
<a >intercept test!</a>
</body>
</html>
4.2 應(yīng)用側(cè)代碼

HarmonyOS中,onInterceptRequest()是一個接口,用于攔截網(wǎng)絡(luò)請求并進(jìn)行處理。它是HarmonyOS的網(wǎng)絡(luò)框架提供的一種擴(kuò)展機(jī)制,可以在網(wǎng)絡(luò)請求發(fā)起之前攔截請求,并進(jìn)行一些自定義的操作。
當(dāng)一個網(wǎng)絡(luò)請求發(fā)起時,HarmonyOS的網(wǎng)絡(luò)框架會首先調(diào)用onInterceptRequest()接口。在該接口中,你可以對請求進(jìn)行一些處理,例如修改請求的URL、添加請求頭、修改請求參數(shù)等。還可以在此處攔截請求,返回自定義的響應(yīng)結(jié)果,以實現(xiàn)一些常見的操作,如模擬網(wǎng)絡(luò)請求,攔截廣告請求等。

import web_webview from '@ohos.web.webview'

@Entry
@Component
struct WebComponent {
  controller: web_webview.WebviewController = new web_webview.WebviewController()
  responseResource: WebResourceResponse = new WebResourceResponse()
  // 開發(fā)者自定義響應(yīng)數(shù)據(jù)
  @State webdata: string = "<!DOCTYPE html>\n" +
  "<html>\n"+
  "<head>\n"+
  "<title>intercept test</title>\n"+
  "</head>\n"+
  "<body>\n"+
  "<h1>intercept test</h1>\n"+
  "</body>\n"+
  "</html>"
  build() {
    Column() {
      Web({ src: $rawfile('local.html'), controller: this.controller })
        .onInterceptRequest((event?: Record<string, WebResourceRequest>): WebResourceResponse => {
          if (!event) {
            return new WebResourceResponse();
          }
          let mRequest: WebResourceRequest = event.request as WebResourceRequest;
          console.info('TAGLee: url:'+ mRequest.getRequestUrl());
          //攔截頁面請求,如果加載的url判斷與目標(biāo)url一致則返回自定義加載結(jié)果webdata
          if(mRequest.getRequestUrl() === 'https://www.example.com/test.html'){
            // 構(gòu)造響應(yīng)數(shù)據(jù)
            this.responseResource.setResponseData(this.webdata);
            this.responseResource.setResponseEncoding('utf-8');
            this.responseResource.setResponseMimeType('text/html');
            this.responseResource.setResponseCode(200);
            this.responseResource.setReasonMessage('OK');
            return this.responseResource;
          }
          return;
        })
    }
  }
}

5.web chrome調(diào)試

1、開啟調(diào)試

在HarmonyOS中,setWebDebuggingAccess()接口用于設(shè)置是否允許調(diào)試Web視圖。

setWebDebuggingAccess()接口的語法如下:

setWebDebuggingAccess(boolean debuggable);

參數(shù)debuggableboolean型,表示是否允許調(diào)試Web視圖。如果debuggable為true,則允許調(diào)試Web視圖;如果debuggablefalse,則禁止調(diào)試Web視圖。
此接口需要在合適的地方調(diào)用,例如在應(yīng)用程序的入口Activity中或者WebView的初始化代碼中調(diào)用。調(diào)用該方法后,系統(tǒng)將根據(jù)參數(shù)的值來決定是否允許調(diào)試Web視圖。
2、 配置端口

// 添加映射 
hdc fport tcp:9222 tcp:9222 
// 查看映射 
hdc fport ls

3、在PC端chrome瀏覽器地址欄中輸入chrome://inspect/#devices,頁面識別到設(shè)備后,就可以開始頁面調(diào)試

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容