To call TypeScript code from html, add specific plugins for JavaScript Proxy registration.
The high-level RegisterJavaScriptProxy, DeleteJavaScriptRegister APIs automate tasks required for JavaScript Registration.
This section contains code samples that show how to use the high-level RegisterJavaScriptProxy
and DeleteJavaScriptRegister
APIs.
First, declare your TypeScript class and create an instance of it, then register it. Your plugin’s extension should be .etslib or .ets. Note that Tuanjie treat .ets files as plugins only if they’re placed in Plugin/OpenHarmony.
The name of register function should match the following format: “Register” + your plugin name.
The filename should be same as class name.
To register the JavaScript Object in Webview, the REGISTER_WEBVIEW_JAVASCRIPT
should be imported and used as below.
// in TestObj.tslib
import { REGISTER_WEBVIEW_JAVASCRIPT } from 'classesLib';
class TestObj {
constructor() {
}
test(testStr: string): string {
console.log('Web Component str: ' + testStr);
return testStr;
}
toString(): void {
console.log('Web Component toString');
}
testNumber(testNum: number): number {
console.log('Web Component number: ' + testNum);
return testNum;
}
asyncTestBool(testBol: boolean): void {
console.log('Web Component boolean: ' + testBol);
}
}
export function RegisterTestObj() {
let register: Record<string, Object> = {};
register["TestObj"] = TestObj;
return register;
}
!!REGISTER_WEBVIEW_JAVASCRIPT && REGISTER_WEBVIEW_JAVASCRIPT("TestObj",TestObj)
Second, in your C# file, create an Webview and call “RegisterJavaScriptProxy”.
using UnityEngine;
using UnityEngine.OpenHarmony;
public class WebviewTest : MonoBehaviour
{
Webview webview;
// Start is called before the first frame update
private void Start()
{
webview = new Webview(100, 100, 100, 100);
webview.Url = "resource://rawfile/Data/StreamingAssets/index.html";
RegisterJavaScript();
webview.Reload();
}
private void RegisterJavaScript()
{
string className = "TestObj"; //Must Same as TypeScript Class Name
string[] methodList = { "test", "toString", "testNumber" };
string[] asyncMethodList = { "asyncTestBool" };
webview.RegisterJavaScriptProxy(className, methodList, asyncMethodList);
}
private void DeleteJavaScript()
{
webview.DeleteJavaScriptRegister("TestObj");
}
private void OnDestroy()
{
DeleteJavaScript();
webview.Reload();
}
}
Finally, in your HTML file, call the TypeScript Object by the registered class.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Merged HTML Example</title>
</head>
<body>
<br><br>
<button type="button" onclick="htmlTest()">Click Me!</button>
<p id="demo"></p>
<script type="text/javascript">
function htmlTest() {
let str=TestObj.test("webtest data");
TestObj.testNumber(1);
TestObj.asyncTestBool(true);
document.getElementById("demo").innerHTML=str;
console.log('TestObj.test result:'+ str)
}
</script>
</body>
</html>
For more usages of JavaScript Proxy, check web-in-page-app-function-invoking.