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内核、鸿蒙南向开发、鸿蒙项目实战)等技术知识点。帮助大家在学习鸿蒙路上快速成长!
鸿蒙【北向应用开发+南向系统层开发】文档
鸿蒙【基础+实战项目】视频
鸿蒙面经
为了避免大家在学习过程中产生更多的时间成本,对比我把以上内容全部放在了↓↓↓想要的可以自拿喔!谢谢大家观看!