gree / unity-webview

zlib License
2.3k stars 694 forks source link

Calling a JS function from EvaluateJS() ? #334

Open youngPadawan07 opened 6 years ago

youngPadawan07 commented 6 years ago

Hi, first of all thank you for your webview that works very well ! I'm having trouble calling a Javascript function from EvaluateJS(), Is there a way to do it ?

KojiNakamaru commented 6 years ago

It should work, as the sample app already does with Unity.call(). The following diff is another example in which we define setBackgroundColor() in sample.js and call it by webViewObject.EvaluateJS(@"setBackgroundColor('#58ACFA')");.

diff --git a/sample/Assets/Scripts/SampleWebView.cs b/sample/Assets/Scripts/SampleWebView.cs
index 79009a7..327dc07 100644
--- a/sample/Assets/Scripts/SampleWebView.cs
+++ b/sample/Assets/Scripts/SampleWebView.cs
@@ -93,6 +93,7 @@ public class SampleWebView : MonoBehaviour
 #endif
 #endif
                 webViewObject.EvaluateJS(@"Unity.call('ua=' + navigator.userAgent)");
+                webViewObject.EvaluateJS(@"setBackgroundColor('#58ACFA')");
             },
             //ua: "custom user agent string",
             enableWKWebView: true);
diff --git a/sample/Assets/StreamingAssets/sample.js b/sample/Assets/StreamingAssets/sample.js
index 8dc3fc4..5399c8a 100644
--- a/sample/Assets/StreamingAssets/sample.js
+++ b/sample/Assets/StreamingAssets/sample.js
@@ -1,12 +1,4 @@
-window.addEventListener(
-    'load',
-    function() {
-        document.body.style.backgroundColor = 'white';
-        window.setTimeout(
-            function() {
-                document.body.style.backgroundColor = '#ABEBC6';
-                var msg = document.getElementById("msg");
-                msg.textContent = '(NOTE: the background color was changed by sample.js, for checking whether the external js code works)';
-            },
-            3000);
-    });
+function setBackgroundColor(color)
+{
+    document.body.style.backgroundColor = color;
+}

The result will be the following: image