How To Call Javascript From C# - Cordova/phonegap
Solution 1:
Try:
webBrowser.InvokeScript("myFunction", "one", "two", "three");
InvokeScript
executes a scripting function defined in the currently loaded document, and passes the function an array of string parameters.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402838%28v=vs.105%29.aspx
Obviously you have to have the JavaScript
function defined in the loaded document.
Depending on your view it may work like this:
this.CordovaView.Browser.InvokeScript("eval", newstring[] { "yourJavascriptFunction(); " });
Solution 2:
I found a solution, admittedly not the best one but works for me.
I created a singleton class called WebViewHandler which looks like this
classWebViewHandler
{
privatestatic WebViewHandler instance;
publicbool isWebViewReady { get { return webView != null; } }
public WPCordovaClassLib.CordovaView webView;
privateWebViewHandler()
{
}
publicvoidsetWebView(ref WPCordovaClassLib.CordovaView webView)
{
this.webView = webView;
}
publicstatic WebViewHandler getInstance()
{
if(instance == null){
instance = new WebViewHandler();
}
return instance;
}
}
Then I set the webview in the constructor on the HomePage like so:
publicHomePage()
{
InitializeComponent();
CordovaView.Loaded += CordovaView_Loaded;
WebViewHandler.getInstance().setWebView(ref CordovaView);
}
Once the WebView is set I can then call InvokeScript from any other class:
WebViewHandler.getInstance().webView.CordovaBrowser.InvokeScript("MyJavaScriptFunctionThatIWishToCall");
Solution 3:
You could use DispatchCommandResult(); as outlined in the cordova documents. That way you can call the c# method, send whatever you need in the callback, and then just execute the javascript from within javascript.
Solution 4:
Try this example :
string str="<script>alert(\"ok\");</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", str, false);
Post a Comment for "How To Call Javascript From C# - Cordova/phonegap"