-
-
Notifications
You must be signed in to change notification settings - Fork 53
Javascript Binding
Tua Rua edited this page May 17, 2020
·
7 revisions
WebViewANE supports two-way communication between Actionscript and Javascript running in the webView.
Javascript can be called as 'fire-and-forget' or we can use an Actionscript closure (i.e. function) to receive the result
Calls Javascript function passing 3 args. Javascript function returns an object which is automatically mapped to an Actionscript Object
webView.callJavascriptFunction("as_to_js", asToJsCallback, 1, "a", 77);
public function asToJsCallback(jsResult:JavascriptResult):void {
trace("asToJsCallback");
trace("jsResult.error", jsResult.error);
trace("jsResult.result", jsResult.result);
trace("jsResult.message", jsResult.message);
trace("jsResult.success", jsResult.success);
var testObject:* = jsResult.result;
trace(testObject);`
}
// function in HTML page
const as_to_js = (numberA, stringA, numberB, obj) => {
console.log(numberA);
console.log(stringA);
console.log(numberB);
console.log(obj);
const person = {
name: "Jim Cowart",
response: {
name: "Chattanooga",
population: 167674
}
};
return isAndroidWebView ? person : JSON.stringify(person);
}
// Set the body background to yellow. No result expected
webView.evaluateJavascript('document.getElementsByTagName("body")[0].style.backgroundColor = "yellow";');
// addcallback in ActionScript **BEFORE** .init() is called
webView.addCallback("js_to_as", jsToAsCallback);
public function jsToAsCallback(asCallback:ActionscriptCallback):void {
trace("asCallback.args", asCallback.args);
trace("asCallback.functionName", asCallback.functionName);
trace("asCallback.callbackName", asCallback.callbackName);
}
// JavaScript code
const isAndroidWebView = /Android/.test(navigator.userAgent);
const isChromium = !isAndroidWebView && navigator.vendor === "Google Inc.";
const isEdge = /Edge/.test(navigator.userAgent);
const isWebKit = !isAndroidWebView && !isChromium && !isEdge;
const webViewANEWrapper = {
postMessage: (message) => { // object
if (isChromium) {
webViewANE.postMessage(message);
} else if (isAndroidWebView) {
webViewANE.postMessage(JSON.stringify(message));
} else if (isEdge) {
window.external.notify(JSON.stringify(message));
} else {
window.webkit.messageHandlers.webViewANE.postMessage(message);
}
}
};
document.addEventListener('DOMContentLoaded', function(){
if (isChromium) {
// Important: CefSharp binding must now be performed async
(async () => {
await window.CefSharp.BindObjectAsync("webViewANE", "bound").then((res) => {
if (res.Success) {
button1.disabled = button2.disabled = false;
}
});
})();
}
});
const messageToPost = {
'functionName': 'js_to_as',
'callbackName': 'jsCallback',
'args': [1, 'I am a string , false]
};
webViewANEWrapper.postMessage(messageToPost);
This work is licensed under Apache License, Copyright (c) 2018 Tua Rua Ltd.
Configuring the ANE
- Windows