HarmonyOS 无法通过H5调用JSBridge展示自定义弹窗?

如题:HarmonyOS 无法通过H5调用JSBridge展示自定义弹窗?

阅读 440
1 个回答

参考示例:

import { ComponentContent } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import web_webview from '@ohos.web.webview';
let uiContext: UIContext | undefined = undefined;
@Entry
@Component
struct Page1 {
  aboutToAppear(): void {
    uiContext = this.getUIContext()
  }
  private webviewController: web_webview.WebviewController = new web_webview.WebviewController();
  private customDialog = new CustomDialog()

  build() {
    Column() {
      Web({src:$rawfile('demo.html'),controller:this.webviewController})
        .javaScriptProxy({
          object: this.customDialog,
          name: "customDialog",
          methodList: ["openDialog"],
          controller: this.webviewController,
        })
    }
  }
}

class CustomDialog{
  openDialog(){
    let promptAction = (uiContext as UIContext).getPromptAction();
    let contentNode = new ComponentContent((uiContext as UIContext), wrapBuilder(buildText));
    try {
      promptAction.openCustomDialog(contentNode);
    } catch (error) {
      let message = (error as BusinessError).message;
      let code = (error as BusinessError).code;
      console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
    };
  }
}

@Builder
function buildText() {
  Column() {
    Text('this is dialog')
      .fontSize(50)
      .fontWeight(FontWeight.Bold)
      .margin({bottom: 36})
  }.backgroundColor('#FFF0F0F0')
}

<!DOCTYPE html>
  <html lang="zh_cn">
  <head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <link rel="icon" href="/favicon.ico">
  <title>测试一下HarmonyOS的web接口</title>
  </head>
  <body>

  <div class="container">
  <p>测试JS调用原生能力</p>
  <button class="login-button"  type="button" onclick="callNative1()">调用原生能力-javaScriptProxy</button>
  <button class="login-button" type="button" onclick="callPromise()">调用原生能力-Promise方式</button>
  <div class="content">
  <div id="demo">
  </div>
  </div>
  </div>

  <div class="container">
  <p>自定义安全键盘</p>
  <div class="tips">请输入账号(6219)交易密码</div>
  <div class="pwd_block">
  <li class="pwd_item"></li>
  <li class="pwd_item"></li>
  <li class="pwd_item"></li>
  <li class="pwd_item"></li>
  <li class="pwd_item"></li>
  </div>

  </div>
  </body>
  </html>
<style>
  .container {
  padding: 40px;
  border: 1px solid red;
  border-radius: 5px;
  margin-bottom: 10px;
}
.title {
  font-size: 20px;
  font-weight: normal ;
}
.content {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}
.item {
  width: 100px;
  height: 100px;
  line-height: 2em;
  border: 1px solid red;
  font-size: 14px;
  border-radius: 10px;
  padding: 0 8px;
  margin: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-button { /* 按钮美化 */
  width: 270px; /* 宽度 */
  height: 40px; /* 高度 */
  border-width: 0px; /* 边框宽度 */
  border-radius: 3px; /* 边框半径 */
  background: #1E90FF; /* 背景颜色 */
  cursor: pointer; /* 鼠标移入按钮范围时出现手势 */
  outline: none; /* 不显示轮廓线 */
  font-family: Microsoft YaHei; /* 设置字体 */
  color: white; /* 字体颜色 */
  font-size: 17px; /* 字体大小 */
  margin-bottom: 20px;
}
.login-button:hover { /* 鼠标移入按钮范围时改变颜色 */
  background: #5599FF;
}

.tips {
  font-weight: bold;
  font-size: 14px;
}

.pwd_block {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  width: 100%;
  margin: 10px 0 40px 0;
}
.pwd_block li {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
  padding-top: 7px;
  margin: 5px;
  text-align: center;
  border: 1px solid #ccc;
  border-radius: 16px;
}

</style>
  <script>
  let showKeyboard = false;
let items = document.querySelectorAll('.pwd_item');
for(let i=0; i<items.length; i++) {
  let item = items[i];
  item.addEventListener('click', () => {
    showKeyboard = !showKeyboard;
    console.log('showKeyboard:', showKeyboard);
    customDialog.openDialog()
      .then((res) => {
        console.log('打开了弹窗');
      })
  });
}

function callNative1() {
  let info = nativeCaller1.getSomeInfo();
  document.getElementById("demo").innerHTML = info;
}

function callPromise() {
  document.getElementById("demo").innerHTML = '';
  nativeCaller1.test().
  then((param) => {
    document.getElementById("demo").innerHTML = param;
    testObjName.toString(param)
  })
    .catch((param) => {
      document.getElementById("demo").innerHTML = param;
      testObjName.toString(param)
    })
}
</script>

以上是beta1能力,如果不升级看下以下的demo:

import promptAction from '@ohos.promptAction'
import {GlobalContext} from '../utils/GlobalContext'
import web_webview from '@ohos.web.webview';

@Builder
export function customDialogBuilder() {
  Column() {
    Text('title ').fontSize(10).fontColor(Color.Red)
    Text('message ').fontSize(10).fontColor(Color.Blue)
    Row() {
      Button("确认").onClick(() => {
        promptAction.closeCustomDialog(AppStorage.get<number>("customDialogId") as number)
      })
      Blank().width(50)
      Button("取消").onClick(() => {
        promptAction.closeCustomDialog(AppStorage.get<number>("customDialogId") as number)
      })
    }
  }.height(100)
}

class CustomDialog{
  openDialog(){
    let that = GlobalContext.getContext().getObject("UIContext")
    if (that){
      promptAction.openCustomDialog({
        builder: customDialogBuilder.bind(that)
      }).then((dialogId: number) => {
        /*let number = AppStorage.get<number>("customDialogId") as number
        console.log('number::::'+number)*/
        AppStorage.setOrCreate("customDialogId",dialogId)
      })
    }
  }
}

@Entry
@Component
struct Page17 {
  aboutToAppear(): void {
    GlobalContext.getContext().setObject("UIContext",this)
  }
  @State message: string = 'Hello World'
  private customDialog = new CustomDialog()
  private webviewController: web_webview.WebviewController = new web_webview.WebviewController();

  build() {
    Row() {
      Column() {
        Web({src:$rawfile('demo.html'),controller:this.webviewController})
          .javaScriptProxy({
            object: this.customDialog,
            name: "customDialog",
            methodList: ["openDialog"],
            controller: this.webviewController,
          })

        Text('dialog').onClick(()=>{
          this.customDialog.openDialog()
        })
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            promptAction.openCustomDialog({
              builder: customDialogBuilder.bind(this)
            }).then((dialogId: number) => {
              /*let number = AppStorage.get<number>("customDialogId") as number
              console.log('number::::'+number)*/
              AppStorage.setOrCreate("customDialogId",dialogId)
            })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
export class GlobalContext {
  private constructor() { }
  private static instance: GlobalContext;
  private _objects = new Map<string, Object>();

  public static getContext(): GlobalContext {
    if (!GlobalContext.instance) {
      GlobalContext.instance = new GlobalContext();
    }
    return GlobalContext.instance;
  }

  getObject(value: string): Object | undefined {
    console.log(typeof (this._objects.get(value)))
    return this._objects.get(value);
  }

  setObject(key: string, objectClass: Object): void {
    this._objects.set(key, objectClass);
  }
}
logo
HarmonyOS
子站问答
访问
宣传栏