JavaScript Execution & Communication
Goal
Execute JavaScript code in the WebView and retrieve results for Unity-WebView interaction.
Actions Required
WebViewCreateInstance
Creates WebView instance
WebViewLoadURL
Loads web content
WebViewShow
Displays WebView
WebViewRunJavaScript
Executes JS code
WebViewGetRunJavaScriptResult
Retrieves JS result
WebViewGetRunJavaScriptError (optional)
Retrieves JS error details
Variables Needed
webViewInstance (Object): Stores the WebView instance
targetURL (String): URL to load
jsScript (String): JavaScript code to execute
jsResult (String): Result from JavaScript execution
Implementation Steps
1. State: CreateAndLoadWebView
Follow Use Case 1 (Basic Browser) to create, load, and show WebView. Wait for WebViewOnLoadFinish success before executing JavaScript.
2. State: ExecuteJavaScript
Action: WebViewRunJavaScript
Inputs:
webViewInstance β From variable
script β jsScript variable
Events:
successEvent β GetResult
failureEvent β GetError (optional) / ShowError
Example Scripts:
Get page title:
"document.title"Get element value:
"document.getElementById('username').value"Call function:
"myFunction('param1', 'param2')"Modify DOM:
"document.body.style.backgroundColor = 'red'"
3. State: GetResult
Action: WebViewGetRunJavaScriptResult
Outputs:
result β jsResult variable
Next: ProcessResult
4. State: ProcessResult
Use the retrieved JavaScript result in Unity (display, save to PlayerPrefs, trigger game logic, etc.)
Optional: State: GetError
Action: WebViewGetRunJavaScriptError
Outputs:
errorCode / errorDescription β Use for UI/logging
Common Issues
JavaScript doesn't execute: Ensure page has finished loading (wait for OnLoadFinish)
Result is empty: Check that JavaScript actually returns a value
Security errors: Some websites block external JavaScript execution
Timing issues: JavaScript must be enabled with
WebViewConfigure(javaScriptEnabled=true)
Flow Diagram
Best Practices
Wait for page load completion before executing JavaScript
Test JavaScript in browser console first to verify syntax
Handle empty/null results gracefully
Use JSON.stringify() in JavaScript to return complex objects as strings
Parse JSON strings in Unity using JsonUtility or similar
Example Use Cases
Extract User Input
Modify Page Appearance
Get Page Data
Call Website Functions
Advanced: Bidirectional Communication
For ongoing communication, combine with Custom URL Schemes (Use Case 3):
Unity β WebView: Use
WebViewRunJavaScriptWebView β Unity: Website calls
window.location = 'unity://callback?data=value'Unity receives: Via
WebViewOnURLSchemeMatchFoundlistener
JavaScript Debugging
If JavaScript fails:
Enable
WebViewConfigure(javaScriptEnabled=true)firstTest script in browser DevTools console
Check for syntax errors in script string
Verify page elements exist (use browser inspector)
Use simple
"'test'"script to verify execution works
Security Considerations
Only execute JavaScript on trusted websites
Validate and sanitize any user input passed to JavaScript
Be aware that JavaScript can access cookies and local storage
Some content security policies may block external script execution
Last updated
Was this helpful?