• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Web Development
2
3## How does the return result of onUrlLoadIntercept affect onInterceptRequest in the \<Web> component?
4
5Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
6
7**Solution**
8
9The operation that follows **onUrlLoadIntercept** is subject to its return result.
10
11-   If **true** is returned, the URL request is intercepted.
12-   If **false** is returned , the **onInterceptRequest** callback is performed.
13
14**Reference**
15
16[onUrlloadIntercept](../reference/arkui-ts/ts-basic-components-web.md#onurlloadinterceptdeprecated)
17
18## What should I do if the onKeyEvent event of the \<Web> component is not triggered as expected?
19
20Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
21
22**Problem**
23
24The **onKeyEvent** event is set for the **\<Web>** component to listen for keyboard events. However, it is not triggered when a key is pressed or lifted.
25
26**Solution**
27
28Currently, the **\<Web>** component does not support the **onKeyEvent** event. To listen for keyboard events for the **\<Web>** component, you can use the **onInterceptKeyEvent** callback function.
29
30**Reference**
31
32[onInterceptKeyEvent](../reference/arkui-ts/ts-basic-components-web.md#oninterceptkeyevent9)
33
34## What should I do if page loading fails when onInterceptRequest is used to intercept URLs and return the custom HTML file?
35
36Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
37
38**Problem**
39
40The **onInterceptRequest** API intercepts URLs specified by **src** and returns the custom HTML file. However, the content in the **script** tag in the HTML file is not loaded.
41
42**Solution**
43
44If only **setResponseData** is set for the interceptor, the kernel cannot identify the HTML file. You must also set parameters such as **setResponseEncoding**, **setResponseMimeType**, and **setResponseHeader** for the kernel to identify the HTML file.
45
46**Example**
47
48```
49Web({ src: 'www.example.com', controller: this.controller })
50  .onInterceptRequest((event) => {
51    console.log('url:' + event.request.getRequestUrl())
52    this.responseweb = new WebResourceResponse();
53    var head1:Header = {
54      headerKey:"Connection",
55      headerValue:"keep-alive"
56    }
57    var length = this.heads.push(head1)
58    this.responseweb.setResponseHeader(this.heads)
59    this.responseweb.setResponseData(this.webdata)
60    this.responseweb.setResponseEncoding('utf-8')
61    this.responseweb.setResponseMimeType('text/html')
62    this.responseweb.setResponseCode(200)
63    this.responseweb.setReasonMessage('OK')
64    return this.responseweb
65})
66```
67
68**Reference**
69
70[WebResourceResponse](../reference/arkui-ts/ts-basic-components-web.md#webresourceresponse)
71
72## How do I execute JS functions in HTML in ArkTS code?
73
74Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
75
76**Solution**
77
78Use the **runJavaScript** API in **WebviewController** to asynchronously execute JavaScript scripts and obtain the execution result in a callback.
79
80>**NOTE**
81>
82>**runJavaScript** can be invoked only after l**oadUrl** is executed. For example, it can be invoked in **onPageEnd**.
83
84**Reference**
85
86[runJavaScript](../reference/apis/js-apis-webview.md#runjavascript)
87
88## How do I invoke an ArkTS method on a local web page loaded in the \<Web> component?
89
90Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
91
92**Solution**
93
941.  Prepare an HTML file. Below is the sample code:
95
96    ```
97    <!DOCTYPE html>
98    <html lang="en">
99    <head>
100        <meta charset="UTF-8">
101        <meta http-equiv="X-UA-Compatible" content="IE=edge">
102        <meta name="viewport" content="width=device-width, initial-scale=1.0">
103        <title>Document</title>
104    </head>
105    <body>
106        <h1>Title</h1>
107        <h5 id="h5"></h5>
108        <h5 id = "h6"></h5>
109        <button onclick="handleFromH5">Invoke ArkTS method </button>
110        <script type="text/javascript">
111            function handleFromH5(){
112                let result = window.objName.test();
113                document.getElementById('h6').innerHTML = result;
114            }
115        </script>
116    </body>
117    </html>
118    ```
119
1202.  Use the **JavaScriptProxy** API in ArkTs to register the object in ArkTS with the window object of H5, and then use the window object to call the method in H5. In the following example, the **testObj** object in ArkTS is registered with the window object of H5 with the alias **objName**. In H5, **window.objName** can then be used to access the object.
121
122    ```
123    // xxx.ets
124    import web_webview from '@ohos.web.webview'
125    @Entry
126    @Component
127    struct Index {
128      @State message: string = 'Hello World'
129      controller: web_webview.WebviewController = new web_webview.WebviewController()
130      testObj = {
131        test: (data1, data2, data3) => {
132          console.log("data1:" + data1);
133          console.log("data2:" + data2);
134          console.log("data3:" + data3);
135          return "AceString";
136        },
137        toString: () => {
138          console.log('toString' + "interface instead.");
139        }
140      }
141      build() {
142        Row() {
143          Column() {
144            Web({ src:$rawfile('index.html'), controller:this.controller })
145              .javaScriptAccess(true)
146              .javaScriptProxy({
147                object: this.testObj,
148                name: "objName",
149                methodList: ["test", "toString"],
150                controller: this.controller,
151             })
152          }
153          .width('100%')
154        }
155        .height('100%')
156      }
157    }
158    ```
159
160
161**Reference**
162
163[javaScriptProxy](../reference/arkui-ts/ts-basic-components-web.md#javascriptproxy)
164
165## How do I set the domStorageAccess attribute of the \<Web> component?
166
167Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
168
169**Solution**
170
171The **domStorageAccess** attribute sets whether to enable the DOM Storage API. By default, this feature is disabled.
172
173**Reference**
174
175[domStorageAccess](../reference/arkui-ts/ts-basic-components-web.md#domstorageaccess)
176
177## What should I do if the network status fails to be detected on the HTML page loaded by the \<Web> component?
178
179Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
180
181**Problem**
182
183When **window.navigator.onLine** is used on the HTML page to obtain the network status, the value is **false** no matter the network connection is set up or not.
184
185**Solution**
186
187Configure the permission for the application to obtain network information: **ohos.permission.GET\_NETWORK\_INFO**.
188
189**Reference**
190
191[GET\_NETWORK\_INFO](../security/permission-list.md#ohospermissionget_network_info)
192
193## How do I set the UserAgent parameter through string concatenation?
194
195Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
196
197**Solution**
198
199By default, the value of **UserAgent** needs to be obtained through the WebviewController. Specifically, it is obtained by calling the **getUserAgent** API in a **WebviewController** object after it is bound to the **\<Web>** component. Therefore, to set **UserAgent** through string concatenation before page loading:
200
2011.  Use @State to define the initial **UserAgent** parameter and bind it to the **\<Web>** component.
2022.  In the **onUrlLoadIntercept** callback of the **\<Web>** component, use **WebviewController.getUserAgent\(\)** to obtain the default **UserAgent** value and update the UserAgent bound to the **\<Web>** component.
203
204**Example**
205
206```
207import web_webview from '@ohos.web.webview'
208@Entry
209@Component
210struct Index {
211  private controller: web_webview.WebviewController = new web_webview.WebviewController()
212  @State userAgentPa: string = ''
213  build() {
214    Row() {
215      Column() {
216        Web({ src: 'http://www.example.com', controller: this.controller }) // Replace the URL with the actual URL.
217          .width('100%')
218          .userAgent(this.userAgentPa)
219          .onUrlLoadIntercept((event) => {
220            let userAgent = this.controller.getUserAgent();
221            this.userAgentPa = userAgent + ' 111111111'
222            return false;
223          })
224      }
225      .width('100%')
226    }
227    .height('100%')
228  }
229}
230```
231
232**Reference**
233
234[userAgent](../reference/arkui-ts/ts-basic-components-web.md#useragent) and [getUserAgent](../reference/apis/js-apis-webview.md#getuseragent)
235
236## How do I enable the \<Web> component to return to the previous web page following a swipe gesture?
237
238Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
239
240**Solution**
241
242Override the **onBackPress** API to define the return logic and use **WebviewController** to determine whether to return to the previous web page.
243
244**Example**
245
246```
247import web_webview from '@ohos.web.webview';
248@Entry
249@Component
250struct Index {
251  controller: web_webview.WebviewController = new web_webview.WebviewController();
252  build() {
253    Column() {
254      Web({ src: 'http://www.example.com', controller: this.controller })// Replace the URL with the actual URL.
255    }
256  }
257  onBackPress() {
258    // Check whether a specific number of steps forward or backward can be performed on the current page. A positive number indicates forward, and a negative number indicates backward.
259    if (this.controller.accessStep(-1)) {
260      this.controller.backward(); // Return to the previous web page.
261      // Execute the custom return logic.
262      return true
263    } else {
264      // Execute the default return logic to return to the previous page.
265      return false
266    }
267  }
268}
269```
270
271**Reference**
272
273[Web](../reference/apis/js-apis-webview.md#accessstep)
274