问题一:以下是将ArkTS对象注册到Web侧的案例。import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
import { PromptAction } from '@kit.ArkUI';
@Entry
@Component
struct WebPage {
controller: webview.WebviewController = new webview.WebviewController();
private prompt: PromptAction = this.getUIContext().getPromptAction();
@State testObj: TestObj = new TestObj(this.prompt);
build() {
Column() {
Button('refresh')
.onClick(() => {
try {
this.controller.refresh();
this.prompt.showToast({message: '成功刷新'});
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
.margin({top: 20, bottom: 20})
Button('Register JavaScript To Window')
.onClick(() => {
try {
// 同时注册同步和异步函数
this.controller.registerJavaScriptProxy(this.testObj, 'objName', ['test']);
this.prompt.showToast({message: '成功注册'});
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
.margin({bottom: 20})
Button('deleteJavaScriptRegister')
.onClick(() => {
try {
this.controller.deleteJavaScriptRegister('objName');
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
.margin({bottom: 20})
Web({ src: $rawfile('testWebPage.html'), controller: this.controller })
.javaScriptAccess(true)
.fileAccess(true)
.geolocationAccess(false)
}
}
}
class TestObj {
prompt: PromptAction | undefined = undefined;
constructor(prompt: PromptAction) {
this.prompt = prompt;
}
test(): void {
if (this.prompt) {
this.prompt.showToast({message: '成功调用ArkUI侧方法'});
}
}
} <!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div style="text-align:center;">
<button type="button" onclick="htmlTest()" style="width:200px;height:80px;font-size:30px;">Click Me!</button>
</div>
<script type="text/javascript">
function htmlTest() {
objName.test();
}
</script>
</body>
</html>