最简单的webview通信与返回

最简单的webview通信与返回

import { webview } from '@kit.ArkWeb'
import { pasteboard } from '@kit.BasicServicesKit'
import promptAction from '@ohos.promptAction'
import { common, Want } from '@kit.AbilityKit'
import { BusinessError } from '@kit.BasicServicesKit'

interface JsBridgeConstructorParams {
  webviewController: webview.WebviewController
  context: common.UIAbilityContext
}

interface CopyParams { text:string, message?: string }

class JsBridge {
  systemPasteboard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard()
  webviewController: webview.WebviewController
  context: common.UIAbilityContext

  constructor(params: JsBridgeConstructorParams) {
    this.webviewController = params.webviewController
    this.context = params.context
  }

  onCopy(params: CopyParams) {
    const data = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, params.text)
    this.systemPasteboard.setData(data, () => {
      promptAction.showToast({
        message: params.message || '复制文本成功',
      })
    })
  }

  onDownload(url: string) {
    this.webviewController.startDownload(url)
  }

  onOpenBrowser(url: string) {
    let want: Want = {
      action: 'ohos.want.action.viewData',
      entities: ['entity.system.browsable'],
      uri: url
    }
    this.context.startAbility(want)
      .then(() => {
        console.error('Start browsableAbility successfully.')
      })
      .catch((err: BusinessError) => {
        console.error(`Failed to startAbility. Code: <span class="katex--inline"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mrow><mi>e</mi><mi>r</mi><mi>r</mi><mi mathvariant="normal">.</mi><mi>c</mi><mi>o</mi><mi>d</mi><mi>e</mi></mrow><mo separator="true">,</mo><mi>m</mi><mi>e</mi><mi>s</mi><mi>s</mi><mi>a</mi><mi>g</mi><mi>e</mi><mo>:</mo></mrow><annotation encoding="application/x-tex">{err.code}, message: </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"><span class="mord"><span class="mord mathnormal" style="margin-right:0.02778em;">err</span><span class="mord">.</span><span class="mord mathnormal">co</span><span class="mord mathnormal">d</span><span class="mord mathnormal">e</span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"><span class="mord mathnormal">m</span><span class="mord mathnormal">ess</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.03588em;">g</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"><span class="mrel">:</span></span></span></span></span>{err.message}`)
      })
  }
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  webviewController: webview.WebviewController = new webview.WebviewController()
  webDownloadDelegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate()
  jsBridge = new JsBridge({ webviewController: this.webviewController, context: getContext(this) as common.UIAbilityContext })


  aboutToAppear(): void {
    // webview.WebviewController.setWebDebuggingAccess(true)
  }

  onBackPress() {
    if(this.webviewController.accessBackward()) {
      this.webviewController.backward()
      return true
    }
    return false
  }

  build() {
    Column() {
      Web({
        src: 'http://192.168.1.4:13000',
        controller: this.webviewController,
      })
        .javaScriptProxy({
          object: this.jsBridge,
          name: "jsBridgeHarmonyOs",
          methodList: ["onCopy", "onDownload", "onOpenBrowser"],
          controller: this.webviewController,
        })
        .onPageEnd(() => {
          console.log('onPageEnd')
          this.webviewController.setDownloadDelegate(this.webDownloadDelegate)
        })
		.onAlert((event) => {
          if (event) {
            console.log("event.url:" + event.url)
            console.log("event.message:" + event.message)
            AlertDialog.show({
              title: '提示',
              message: event.message,
              primaryButton: {
                value: 'ok',
                action: () => {
                  event.result.handleCancel()
                }
              }
            })
          }
          return true
        })
    }
  }
}
</span></span></span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值