How to call JavaScript from C# - Cordova/PhoneGap

前端 未结 4 898
生来不讨喜
生来不讨喜 2021-01-18 05:10

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 cla

4条回答
  •  遥遥无期
    2021-01-18 05:54

    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");
    

提交回复
热议问题