当前位置: 首页 > news >正文

鸿蒙应用框架开发【JS注入与执行】 Web

JS注入与执行

介绍

本示例基于H5游戏,通过arkui的button实现对游戏实现基本控制,展示webview的JS注入与执行能力,及native应用与H5的通信能力。

效果预览

1

使用说明

1.设备连接热点,可访问互联网。

2.打开应用,通过界面中按钮进行游戏控制。

具体实现

  • 本示例分成一个模块

    • 通过button实现对游戏的基本控制,WebviewController方法控制Web组件各种行为,使用webview注入JS与执行能力。
      源码:[EntryAbility.ets]
/** Copyright (c) 2023 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import { hilog } from '@kit.PerformanceAnalysisKit';
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';export default class EntryAbility extends UIAbility {onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? '');hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? '');}onDestroy() {hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');}onWindowStageCreate(windowStage: window.WindowStage) {// Main window is created, set main page for this abilityhilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');windowStage.loadContent('pages/Index', (err, data) => {if (err.code) {hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.ERROR);hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');return;}hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');});}onWindowStageDestroy() {// Main window is destroyed, release UI related resourceshilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');}onForeground() {// Ability has brought to foregroundhilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');}onBackground() {// Ability has back to backgroundhilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');}
}

源码[Index.ets]

/** Copyright (c) 2022 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/
import { webview } from '@kit.ArkWeb';
import Logger from '../model/Logger';const TAG: string = '[Index]';@Entry
@Component
struct Index {@State gameLeft: string = "console.info('webgame gameLeft'); _main.paddle.moveLeft();";@State gameRight: string = "console.info('webgame gameRight'); _main.paddle.moveRight();";@State gameStart: string = "console.info('webgame gameStart'); if (_main.game.state !== _main.game.state_GAMEOVER) {_main.game.state = _main.game.state_RUNNING; _main.ball.fired = true;}";@State gameReset: string = "console.info('webgame gameReset'); if (_main.game.state === _main.game.state_GAMEOVER) {_main.game.state = _main.game.state_START; _main.start()}";@State removeDesc: string = "console.info('webgame removeDesc'); y=document.getElementsByTagName('div')[0]; y.parentNode.removeChild(y)";private imgRequestUrl: string = 'https://yangyunhe369.github.io/h5-game-blockBreaker/images/background.jpg';controller: webview.WebviewController = new webview.WebviewController();responseweb: WebResourceResponse = new WebResourceResponse();build() {Row() {Column() {Button('Start', { type: ButtonType.Capsule }).onClick(() => {try {this.controller.loadUrl("javascript:" + this.gameStart);} catch (error) {Logger.info(TAG, `loadUrl gameStart fail: ${JSON.stringify(error)}`);}})Button('L', { type: ButtonType.Capsule }).width(50).height(100).backgroundColor(Color.Red).gesture(LongPressGesture({ repeat: true, duration: 20 }).onAction((event: GestureEvent) => {if (event.repeat) {try {this.controller.loadUrl("javascript:" + this.gameLeft);} catch (error) {Logger.info(TAG, `loadUrl gameLeft fail: ${JSON.stringify(error)}`);}}}))}.width('8%')Column() {Web({ src: "https://yangyunhe369.github.io/h5-game-blockBreaker/", controller: this.controller }).domStorageAccess(true).onlineImageAccess(true).imageAccess(true).zoomAccess(false).javaScriptAccess(true).backgroundColor(Color.Orange)//拦截资源请求,优化游戏流畅度.onInterceptRequest((event) => {let url = '';if (event) {url = event.request.getRequestUrl();}if (url === this.imgRequestUrl) {return this.responseweb;}return null;}).onPageEnd(e => {try {this.controller.loadUrl("javascript:" + this.removeDesc);} catch (error) {Logger.info(TAG, `loadUrl removeDesc fail: ${JSON.stringify(error)}`);}})}.width('78%')Column() {Button('Reset', { type: ButtonType.Capsule }).onClick(() => {try {this.controller.loadUrl("javascript:" + this.gameReset);} catch (error) {Logger.info(TAG, `loadUrl gameReset fail: ${JSON.stringify(error)}`);}})Button('R', { type: ButtonType.Capsule }).width(50).height(100).backgroundColor(Color.Red).gesture(LongPressGesture({ repeat: true, duration: 20 }).onAction((event: GestureEvent) => {if (event.repeat) {try {this.controller.loadUrl("javascript:" + this.gameRight);} catch (error) {Logger.info(TAG, `loadUrl gameRight fail: ${JSON.stringify(error)}`);}}}))}.width('8%')}}
}
  • 接口参考:@ohos.window,@ohos.web.webview

以上就是本篇文章所带来的鸿蒙开发中一小部分技术讲解;想要学习完整的鸿蒙全栈技术。可以在结尾找我可全部拿到!
下面是鸿蒙的完整学习路线,展示如下:
1

除此之外,根据这个学习鸿蒙全栈学习路线,也附带一整套完整的学习【文档+视频】,内容包含如下

内容包含了:(ArkTS、ArkUI、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、鸿蒙南向开发、鸿蒙项目实战)等技术知识点。帮助大家在学习鸿蒙路上快速成长!

鸿蒙【北向应用开发+南向系统层开发】文档

鸿蒙【基础+实战项目】视频

鸿蒙面经

在这里插入图片描述

为了避免大家在学习过程中产生更多的时间成本,对比我把以上内容全部放在了↓↓↓想要的可以自拿喔!谢谢大家观看!

http://www.lryc.cn/news/412157.html

相关文章:

  • AI问答:理解 DRG / Diagnosis Related Group / 按疾病诊断相关分组
  • 多个线程同时调用接口
  • 本科阶段最后一次竞赛Vlog——2024年智能车大赛智慧医疗组准备全过程——1到手测试
  • 2024第三届钉钉杯大学生大数据挑战赛【A题】完整分享
  • 下面关于数组排序的说明那项是错误的?
  • 【第二篇章】优秀的机器学习策略 超参数优化之决策树
  • httprunner转载
  • 反序列化漏洞vulhub靶场serial
  • C++ 文件流详解
  • docker compse简介与安装
  • 基于深度学习的零样本学习
  • C++——list容器以及手动实现
  • Win11系统文件资源管理器鼠标右键卡顿解决方法
  • 零基础学Python之 第十八讲 文件读写
  • 检索增强生成(RAG):智能内容生成的新纪元
  • ubuntu2204安装elasticsearch7.17.22
  • 介绍Servlet后端中两种接收参数方式req.getAttributer和req.getParameter的区别
  • Delphi FMX安卓Android播放mp3音频内存流
  • MapUtils常用方法
  • 自定义PasswordEditText控件,在手机字体应用后,字体样式未发生改变
  • 学习打卡第31天
  • opencascade AIS_TexturedShape源码学习 贴纹理
  • C# winform 串口读取字节流,MB级别字节流
  • 创建一个简单的单链表
  • 15.1 Zookeeper简介安装及基础使用
  • 详细说明Java中Map和Set接口的使用方法
  • CSS3 scale 适配
  • SX_初识GitLab_1
  • 这才是 PHP 高性能框架 Workerman 的立命之本
  • Python——记录pip问题(解决下载慢、升级失败问题)