Calling Frontend JavaScript Functions from HarmonyOS Next Applications
Overview
In HarmonyOS Next, the runJavaScript()
and runJavaScriptExt()
methods allow applications to invoke JavaScript functions on the frontend page. These methods facilitate seamless interaction between the application and the frontend, enabling dynamic updates and responses based on user actions or application logic.
Method Comparison
-
runJavaScript()
andrunJavaScriptExt()
differ in parameter types:-
runJavaScriptExt()
supports not onlystring
but alsoArrayBuffer
parameters, allowing JavaScript script data to be obtained from files. -
runJavaScriptExt()
can retrieve execution results viaAsyncCallback
.
-
Example Usage
Frontend Page Code
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="callArkTS()">Click Me!</button>
<h1 id="text">This is a test message. Default text color is black. After calling runJavaScript, the text color turns green. After calling runJavaScriptCodePassed, the text color turns red.</h1>
<script>
// Implementation for calling a function with parameters
var param = "param: JavaScript Hello World!";
function htmlTest(param) {
document.getElementById('text').style.color = 'green';
console.log(param);
}
// Implementation for calling a function without parameters
function htmlTest() {
document.getElementById('text').style.color = 'green';
}
// Triggered by "Click Me!" button to execute JavaScript code passed from the application side
function callArkTS() {
changeColor();
}
</script>
</body>
</html>
Application-Side Code
// xxx.ets
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
webviewController: webview.WebviewController = new webview.WebviewController();
aboutToAppear() {
// Configure Web to enable debugging mode
webview.WebviewController.setWebDebuggingAccess(true);
}
build() {
Column() {
Button('Run JavaScript')
.onClick(() => {
// When the frontend function has no parameters, omit 'param'.
this.webviewController.runJavaScript('htmlTest()');
})
Button('Run JavaScript Code Passed')
.onClick(() => {
// Pass JavaScript code from the application side.
this.webviewController.runJavaScript(`function changeColor(){document.getElementById('text').style.color = 'red'}`);
})
Web({ src: $rawfile('index.html'), controller: this.webviewController })
}
}
}
Explanation
-
Frontend Page: The HTML page includes a button and a heading. The button triggers the
callArkTS()
function, which in turn callschangeColor()
, changing the text color to red. ThehtmlTest()
function changes the text color to green and logs a message to the console. -
Application-Side Code: The application includes two buttons. The
Run JavaScript
button calls thehtmlTest()
function on the frontend page. TheRun JavaScript Code Passed
button passes a JavaScript function as a string to the frontend, which changes the text color to red when executed.