鸿蒙应用框架开发【JS注入与执行】 Web
JS注入与执行
介绍
本示例基于H5游戏,通过arkui的button实现对游戏实现基本控制,展示webview的JS注入与执行能力,及native应用与H5的通信能力。
效果预览

使用说明
1.设备连接热点,可访问互联网。
2.打开应用,通过界面中按钮进行游戏控制。
具体实现
-
本示例分成一个模块
- 通过button实现对游戏的基本控制,WebviewController方法控制Web组件各种行为,使用webview注入JS与执行能力。
源码:[EntryAbility.ets]
- 通过button实现对游戏的基本控制,WebviewController方法控制Web组件各种行为,使用webview注入JS与执行能力。
/** 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
以上就是本篇文章所带来的鸿蒙开发中一小部分技术讲解;想要学习完整的鸿蒙全栈技术。可以在结尾找我可全部拿到!
下面是鸿蒙的完整学习路线,展示如下:

除此之外,根据这个学习鸿蒙全栈学习路线,也附带一整套完整的学习【文档+视频】,内容包含如下:
内容包含了:(ArkTS、ArkUI、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、鸿蒙南向开发、鸿蒙项目实战)等技术知识点。帮助大家在学习鸿蒙路上快速成长!
鸿蒙【北向应用开发+南向系统层开发】文档
鸿蒙【基础+实战项目】视频
鸿蒙面经

为了避免大家在学习过程中产生更多的时间成本,对比我把以上内容全部放在了↓↓↓想要的可以自拿喔!谢谢大家观看!
相关文章:
鸿蒙应用框架开发【JS注入与执行】 Web
JS注入与执行 介绍 本示例基于H5游戏,通过arkui的button实现对游戏实现基本控制,展示webview的JS注入与执行能力,及native应用与H5的通信能力。 效果预览 使用说明 1.设备连接热点,可访问互联网。 2.打开应用,通过…...
AI问答:理解 DRG / Diagnosis Related Group / 按疾病诊断相关分组
DRG(Diagnosis Related Group)系统,中文译作“按疾病诊断相关分组”,是一种根据病情临床相似程度和资源消耗水平将住院病人进行分组的系统。以下是对DRG系统的详细理解: 一、定义与原理 1.1、定义:DRG系统…...
多个线程同时调用接口
1、线程的基本概念 线程是程序执行的最小单元。每个线程可以独立执行一段代码,与其他线程并行运行。Java提供Thread类和Runnable接口来创建和管理线程。 2、创建线程 1)继承Thread类并重写run()方法: class MyThread extend Thread{ pub…...
本科阶段最后一次竞赛Vlog——2024年智能车大赛智慧医疗组准备全过程——1到手测试
本科阶段最后一次竞赛Vlog——2024年智能车大赛智慧医疗组准备全过程——1到手测试 大家好,今天给大家带来的是购买到小车或者说RDK X3之后直接快速体验,今天主要围绕官方的快速入门手册进行逐步测试 1.知识补充1 在这里首先要给新手小白补充几…...
2024第三届钉钉杯大学生大数据挑战赛【A题】完整分享
2024第三届钉钉杯大学生大数据挑战赛已经开赛,小编给大家带来非常实用的助力【A题】完整,(看图片下方的说明),资料预览: 微信公众号...
下面关于数组排序的说明那项是错误的?
下面关于数组排序的说明那项是错误的? A. java.util.Arrays类提供有数组排序的支持方法:sort(); B. 通过java.util.Arrays类排序的对象所在类需要实现Comparable或Comparator接口; C. String数组可以进行排序,是因为St…...
【第二篇章】优秀的机器学习策略 超参数优化之决策树
在机器学习的浩瀚星空中,决策树作为一颗璀璨的星辰,以其直观易懂、解释性强以及高效处理分类与回归任务的能力,赢得了众多数据科学家与工程师的青睐。随着大数据时代的到来,如何从海量数据中提炼出有价值的信息,构建出…...
httprunner转载
基于 HttpRunner4.0 的接口自动化测试实践 测试之家 from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase # 配置数据库连接信息 config ( Config("database test") .variables( **{ "db_host": &…...
反序列化漏洞vulhub靶场serial
环境搭建 下载 https://download.vulnhub.com/serial/serial.zip 解压出来就是这种 你会得到一个这样的文件,这里使用VMware新建一个虚拟机,这里记录比较重要的几部分。 这里就是使用我们刚才下过来的。 漏洞过程详解 1.信息收集 打开靶机࿰…...
C++ 文件流详解
在 C 中,文件处理是一个常见且重要的任务。标准库提供了三种主要的文件流类来处理文件输入和输出:fstream、ifstream 和 ofstream。这些类都在 <fstream> 头文件中定义。 一、fstream 类 fstream 是文件流类的基类,既可以用于读操作&…...
docker compse简介与安装
目录 1. Docker Compose 简介 2. Docker Compose 安装 2.1 在 Ubuntu 上安装 Docker Compose 2.1.1 通过 apt 安装 2.1.2 使用官方脚本安装最新版本 2.2 在 CentOS 上安装 Docker Compose 2.2.2 使用官方脚本安装最新版本 2.2.3 使用 pip 安装 2.3 在 openEuler 上安装…...
基于深度学习的零样本学习
零样本学习(Zero-Shot Learning, ZSL)是深度学习中的一个前沿研究领域,其目标是在没有见过目标类别的样本的情况下,对这些新类别进行识别或分类。这种方法特别适用于在实际应用中存在大量未标注类别或新类别不断涌现的场景&#x…...
C++——list容器以及手动实现
LIST容器 list概述列表容器属性例子 list函数构造函数默认构造函数:带有元素个数和元素初值的构造函数:范围构造函数:拷贝构造函数:移动构造函数:示例 赋值运算符重载拷贝赋值操作符 (1):移动赋值操作符 (2…...
Win11系统文件资源管理器鼠标右键卡顿解决方法
引用链接: Windows 11文件资源管理器崩溃怎么解决?看看这7个解决办法!...
零基础学Python之 第十八讲 文件读写
当你开始学习Python编程时,文件读写是一个非常基础且重要的技能。本篇博客将引导你从零开始学习如何在Python中进行文件读写操作。 1. 打开文件 在Python中,要操作一个文件,首先需要打开它。使用内置的 open() 函数来打开文件,语…...
检索增强生成(RAG):智能内容生成的新纪元
引言 在大 AI 时代,生成式人工智能(GenAI)模型,尤其是大型语言模型(LLM),已经展现出了令人瞩目的能力。然而,这些模型在提供信息的准确、即时、专业、权威等方面仍存在局限。检索增…...
ubuntu2204安装elasticsearch7.17.22
下载安装 wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.17.22-amd64.deb wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.17.22-amd64.deb.sha512 shasum -a 512 -c elasticsearch-7.17.22-amd64.deb.sha512 su…...
介绍Servlet后端中两种接收参数方式req.getAttributer和req.getParameter的区别
数据来源 getParameter:此方法用于获取客户端发送的请求中携带的参数,通常这些参数是通过HTTP GET或POST请求传递的表单数据。例如,用户填写的用户名和密码等输入信息。getAttribute:该方法用来获取在服务器端通过setAttribute方法…...
Delphi FMX安卓Android播放mp3音频内存流
【笔记:安卓开发JavaDelphi FMX】 Delphi FMX跨平台的MediaPlayer无法播放音频数据流只能打开音频文件播放,但有时候需要直接播放内存流数据而无需生成文件,可以通过把内存流转ByteArray再通过Android平台系统原生的MediaDataSource或ParcelF…...
MapUtils常用方法
1、摘要 MapUtils是一个用于处理Map对象的实用工具类,它提供了许多方便的方法来执行常见的操作,如获取值、设置默认值、合并Map等。本文将介绍MapUtils的常见用法,以帮助你更轻松地处理Map数据。 2、前言 在Java编程中,Map是一…...
RevokeMsgPatcher:PC端即时通讯工具消息控制解决方案
RevokeMsgPatcher:PC端即时通讯工具消息控制解决方案 【免费下载链接】RevokeMsgPatcher :trollface: A hex editor for WeChat/QQ/TIM - PC版微信/QQ/TIM防撤回补丁(我已经看到了,撤回也没用了) 项目地址: https://gitcode.com…...
PyFluent:3大核心场景实现CFD仿真全流程自动化
PyFluent:3大核心场景实现CFD仿真全流程自动化 【免费下载链接】pyfluent 项目地址: https://gitcode.com/gh_mirrors/pyf/pyfluent 计算流体动力学(CFD)仿真作为工程设计的关键环节,长期面临流程繁琐、迭代低效、跨学科协…...
避坑指南:Double DQN和Dueling DQN在TensorFlow 2.x中的5个常见实现错误
Double DQN与Dueling DQN在TensorFlow 2.x中的五大工程陷阱与解决方案 当你在深夜调试强化学习模型时,是否遇到过这种情况:训练曲线像过山车一样剧烈波动,明明采用了Double DQN或Dueling DQN这些改进算法,效果却比基础DQN还要差&a…...
nli-distilroberta-base代码实例:Python调用DistilRoBERTa实现Entailment识别
nli-distilroberta-base代码实例:Python调用DistilRoBERTa实现Entailment识别 1. 项目概述 自然语言推理(Natural Language Inference, NLI)是自然语言处理中的一项重要任务,用于判断两个句子之间的逻辑关系。nli-distilroberta-base是基于DistilRoBER…...
告别蜗牛速度!优麒麟20.04 LTS换源华为云镜像保姆级教程
优麒麟20.04 LTS提速指南:华为云镜像配置全解析 每次在优麒麟上安装软件时,看着进度条像蜗牛一样缓慢前进,是不是让你感到无比焦虑?特别是当你急需某个工具完成工作时,漫长的等待简直让人抓狂。作为一款基于Ubuntu的国…...
ssm+java2026年毕设私教预约系统【源码+论文】
本系统(程序源码)带文档lw万字以上 文末可获取一份本项目的java源码和数据库参考。系统程序文件列表开题报告内容一、选题背景关于会议管理问题的研究,现有研究主要以传统纸质登记和简单的OA系统为主,专门针对智能化、全流程会议预…...
MarkDownload:让网页转Markdown变得简单高效的浏览器扩展
MarkDownload:让网页转Markdown变得简单高效的浏览器扩展 【免费下载链接】markdownload A Firefox and Google Chrome extension to clip websites and download them into a readable markdown file. 项目地址: https://gitcode.com/gh_mirrors/ma/markdownload…...
深入解析卷积层参数量与FLOPs的计算原理及优化策略
1. 卷积层参数量计算原理 要理解卷积层的参数量计算,我们先从一个实际例子入手。假设有个输入特征图尺寸是64643(HWC),卷积核大小33,输出通道数64,带偏置项。这时候参数量是多少呢? 参数量的构…...
HarmonyOS 5 + UniApp 真机调试保姆级教程:从HBuilderX配置到ArkUI Inspector查错
HarmonyOS 5 UniApp 真机调试全流程实战指南 第一次在HarmonyOS设备上调试UniApp应用时,我盯着HBuilderX里那个灰色的"运行到鸿蒙设备"按钮整整半小时。设备明明连着USB线,开发者模式也开了,但工具就是识别不到我的MatePad Pro。…...
Mermaid在线编辑器:技术图表制作的高效解决方案
Mermaid在线编辑器:技术图表制作的高效解决方案 【免费下载链接】mermaid-live-editor Edit, preview and share mermaid charts/diagrams. New implementation of the live editor. 项目地址: https://gitcode.com/GitHub_Trending/me/mermaid-live-editor …...
