HarmonyOS 如何在webview中使用localStorage?

如何在webview中使用localStorage?现在在项目中出现如下报错:

var token = localStorage.getItem("token"); 
index/:110 Uncaught TypeError: Cannot read properties of null (reading 'getItem')
阅读 553
1 个回答

可参考以下示例:

import { webview } from '@kit.ArkWeb';

@Entry
@Component
struct Index {
  controller: webview.WebviewController = new webview.WebviewController();
  @State webResult: string = '';

  build() {
    Column() {
      Text(this.webResult).fontSize(20);
      Image($r('app.media.test')).height(100).width(200).draggable(false)
      Web({ src: $rawfile('index.html'), controller: this.controller })
        .javaScriptAccess(true)
        .domStorageAccess(true)
        .onPageEnd(() => {
          // 获取 localStorage 的值 
          this.controller.runJavaScript('localStorage.setItem("COOKIE13", "Test_Data");')
            .then(() => {
              return this.controller.runJavaScript(`localStorage.getItem("COOKIE13")`)
            })
            .then((result: string) => {
              if (typeof result === 'string') {
                console.log('I got the item: ' + result);
                this.webResult = result;
              } else {
                console.error('Unexpected result type:', result);
              }
            })
            .catch((error: string) => {
              console.error('Error running JavaScript:', error);
            });
        });
    }
  }
} 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进