HarmonyOS 鸿蒙Next代码片段分享-如何实现混合开发的离线包
HarmonyOS 鸿蒙Next代码片段分享-如何实现混合开发的离线包
封装 ArkWeb
import { webview } from ‘@kit.ArkWeb’;
import JsBridge from ‘./JsBridge’;
@Component
struct Index {
controller: webview.WebviewController = new webview.WebviewController();
@Prop src: string | Resource = ‘’;
@Prop isOffline: boolean = true;
@State jsBridge: JsBridge = new JsBridge();
aboutToAppear() {
// 配置Web开启调试模式
webview.WebviewController.setWebDebuggingAccess(true);
}
getMimeType(filePath: string) {
let mimeType = ‘’;
if (filePath.endsWith(’.html’)) {
mimeType = ‘text/html’;
} else if (filePath.endsWith(’.css’)) {
mimeType = ‘text/css’;
} else if (filePath.endsWith(’.js’)) {
mimeType = ‘application/javascript’;
} else if (filePath.endsWith(’.svg’)) {
mimeType = ‘image/svg+xml’;
} else if (filePath.endsWith(’.png’)) {
mimeType = ‘image/png’;
} else if (filePath.endsWith(’.jpg’)) {
mimeType = ‘image/jpeg’;
} else if (filePath.endsWith(’.map’)) {
mimeType = ‘application/js’;
} else if (filePath.endsWith(’.json’)) {
mimeType = ‘application/json’;
} else if (filePath.endsWith(’.png’)) {
mimeType = ‘image/png’;
} else if (filePath.endsWith(’.bin’)) {
mimeType = ‘application/octet-stream’;
} else if (filePath.endsWith(’.wasm’)) {
mimeType = ‘application/wasm’;
}
<span class="hljs-keyword"><span class="hljs-keyword">return</span></span> mimeType
}
build() {
Web({ src: this.src, controller: this.controller })
.domStorageAccess(true)
.javaScriptProxy({
object: this.jsBridge,
name: ‘jsBridge’,
methodList: this.jsBridge.methodList,
controller: this.controller
})
.onInterceptRequest(this.isOffline ? event => {
const rawFilePath = event.request.getRequestUrl().replace(‘http://localhost/’, ‘’)
const webResourceResponse = new WebResourceResponse();
webResourceResponse.setResponseEncoding(“UTF-8”);
webResourceResponse.setResponseCode(200);
webResourceResponse.setResponseData($rawfile(rawFilePath));
webResourceResponse.setResponseMimeType(this.getMimeType(rawFilePath));
return webResourceResponse;
} : undefined)
}
}
export default Index;
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
使用
import WebContainer from ‘…/components/WebContainer’;
@Entry
@Component
struct Index {
@State message: string = ‘Hello World’;
build() {
RelativeContainer() {
WebContainer({
src: ‘http://localhost/index.html’,
isOffline: true,
})
}
.height(‘100%’)
.width(‘100%’)
}
}
<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>
更多关于HarmonyOS 鸿蒙Next代码片段分享-如何实现混合开发的离线包的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html