• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Setting Back-forward Cache
2
3By enabling the back-forward cache for **Web** components, you can navigate through the visited pages smoother and faster.
4
5## Enabling Back-forward Cache
6
7You can use [enableBackForwardCache()](../reference/apis-arkweb/js-apis-webview.md#enablebackforwardcache12) to enable the back-forward cache for the **Web** component.
8
9This API must be called before calling [initializeWebEngine()](../reference/apis-arkweb/js-apis-webview.md#initializewebengine) to initialize the kernel.
10
11```ts
12// EntryAbility.ets
13import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
14import { hilog } from '@kit.PerformanceAnalysisKit';
15import { window } from '@kit.ArkUI';
16import { webview } from '@kit.ArkWeb';
17
18export default class EntryAbility extends UIAbility {
19    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
20        let features = new webview.BackForwardCacheSupportedFeatures();
21        features.nativeEmbed = true;
22        features.mediaTakeOver = true;
23        webview.WebviewController.enableBackForwardCache(features);
24        webview.WebviewController.initializeWebEngine();
25        AppStorage.setOrCreate("abilityWant", want);
26    }
27}
28```
29
30## Setting the Size and Live Time of Cached pages
31
32You can use [setBackForwardCacheOptions()](../reference/apis-arkweb/js-apis-webview.md#setbackforwardcacheoptions12) to set the back-forward cache options for each **Web** component.
33
34In the following example, the maximum number of pages that can be cached in the **Web** component is set to **10**, and each page is cached for 300s.
35
36```ts
37// xxx.ts
38import { webview } from '@kit.ArkWeb';
39
40@Entry
41@Component
42struct Index {
43  controller: webview.WebviewController = new webview.WebviewController();
44
45  build() {
46    Column() {
47      Row() {
48        Button("Add options").onClick((event: ClickEvent) => {
49          let options = new webview.BackForwardCacheOptions();
50          options.size = 10;
51          options.timeToLive = 300;
52          this.controller.setBackForwardCacheOptions(options);
53        })
54        Button("Backward").onClick((event: ClickEvent) => {
55          this.controller.backward();
56        })
57        Button("Forward").onClick((event: ClickEvent) => {
58          this.controller.forward();
59        })
60      }
61      Web({ src: "https://www.example.com", controller: this.controller })
62    }
63    .height('100%')
64    .width('100%')
65  }
66}
67```
68