Call the front-end page function

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
varparam="param: JavaScript Hello World!";functionhtmlTest(param){document.getElementById('text').style.color='green';console.log(param);}functionhtmlTest(){document.getElementById('text').style.color='green';}functioncallArkTS(){changeColor();}
Application-Side Code
import{webview}from'@kit.ArkWeb';@Entry@ComponentstructWebComponent{webviewController:webview.WebviewController=newwebview.WebviewController();aboutToAppear(){webview.WebviewController.setWebDebuggingAccess(!0);}build(){Column(){Button('Run JavaScript').onClick(()=>{this.webviewController.runJavaScript('htmlTest()');})Button('Run JavaScript Code Passed').onClick(()=>{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.