Search code examples
c#javascriptcordovawindows-phone-8invokescript

Error UnathorizedException when invoking JavaScript from C#


I am trying to call JavaScript code from C# in a PhoneGap (Cordova) Windows Phone 8 application. Following the steps of this accepted answer thread: How to call JavaScript from C# - Cordova/PhoneGap

I am supposed to be able to access a method in the Javascript part or execute a hardcoded JS code. But, I am encountering this error:

An exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary
A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll but was not handled in user code
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.ni.dll
An exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary
ERROR: Exception in ProcessCommand :: Exception has been thrown by the target of an invocation.
ERROR: failed to InvokeMethodNamed :: pluginMethod on Object :: Example

My code is (is a native Plugin):

namespace WPCordovaClassLib.Cordova.Commands
{
    public class Example : Cordova.Commands.BaseCommand
    {
        public void pluginMethod(string options)
        {
          //The error is caused in this line
          PGWebBrowserHandler.getInstance().webView.CordovaBrowser
              .InvokeScript("eval", 
                            new string[] { "alert('Is it running?!');" });
        }
    }
}

PGWebBrowserHandler is the name of the singleton class given in the previous mentioned thread in order to have access to the CordovaBrowser from any C# class.

The error (FileNotFoundException, UnauthorizedAccessException and TargetInvocationException) is not caused by the InvokeScript() method, is caused previously by obtaining the webView, which doesn't crash but debugging it, a lot of is methods are causing UnauthorizedAccessException.

I hope my explanations are clear. I've been searching it in Google but I've not found a solution or workaround anywhere. Anybody know the reason of these problems? Invoking the invokeScript() method from the MainPage.cs also cause exceptions.


Solution

  • try this code:

    Dispatcher.BeginInvoke(
                () =>
                {
                    PGWebBrowserHandler.getInstance().webView.CordovaBrowser
                        .InvokeScript("eval",
                          new string[] { "alert('Is it running?!');" });
                });