How to call JavaScript from C# - Cordova/PhoneGap

2020-04-05 07:57发布

I'm using cordova/phonegap to make a windows phone app, i'm trying to call a script from C# when an event fires.

Is there anyway to do this?

here's my class so far.

public void register(string options)
{
        // This is executed asynchronously
        if (!TryFindChannel())
            DoConnect();
}


void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
        // Finished asynchronous task in "register" method
        Trace("Channel opened. Got Uri:\n" + httpChannel.ChannelUri.ToString());
        SaveChannelInfo();

        Trace("Subscribing to channel events");
        SubscribeToService();
        SubscribeToNotifications();

        // SEND CHANNEL URI TO JAVASCRIPT

}

4条回答
【Aperson】
2楼-- · 2020-04-05 08:06

I found a solution, admittedly not the best one but works for me.

I created a singleton class called WebViewHandler which looks like this

class WebViewHandler
{
    private static WebViewHandler instance;
    public bool isWebViewReady { get { return webView != null; } }
    public WPCordovaClassLib.CordovaView webView;

    private WebViewHandler()
    {

    }

    public void setWebView(ref WPCordovaClassLib.CordovaView webView)
    {
        this.webView = webView;
    }

    public static WebViewHandler getInstance()
    {
        if(instance == null){
            instance = new WebViewHandler();
        }
        return instance;
    } 
}

Then I set the webview in the constructor on the HomePage like so:

 public HomePage()
 {
      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");
查看更多
We Are One
3楼-- · 2020-04-05 08:21

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.

查看更多
再贱就再见
4楼-- · 2020-04-05 08:24

Try this example :

string str="<script>alert(\"ok\");</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", str, false);
查看更多
够拽才男人
5楼-- · 2020-04-05 08:25

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", new string[] { "yourJavascriptFunction(); " });
查看更多
登录 后发表回答