Cordova throwing exception Cross origin requests are only supported for protocol schemes

938 views Asked by At

I am very new to Cordova framework. I am trying to access HTML file from Droidgap activity, but getting exception as,

Cross-origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, https.

For this I found one link, maybe you will find this question as a duplicate, but I am looking for Android solution, they are saying to install local server and then try to access this HTML, but in my case I want it to be accessible in MainActivity.

following is code..

public class MainActivity extends DroidGap {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.appView.getSettings().setAllowFileAccess(true); //this line throws nullPointerException for appView
        super.appView.getSettings().setAllowFileAccessFromFileURLs(true);
        super.appView.getSettings().setAllowUniversalAccessFromFileURLs(true);

        super.loadUrl("file:///android_asset/www/MyHtml.html");
    }
}

My HTML is located at asset/www/MyHtml.html

I am really struggling with this issue, can anyone help to get out of this?

1

There are 1 answers

3
Jon Goodwin On BEST ANSWER

You say:

Cross-origin requests are only supported for protocol schemes: HTTP, data, chrome, chrome-extension, https.

You also say (in comment):

In this case I am getting appView variable as null, NullpointerException

First get the appView with the getView() method, and use a local variable:

WebView myappView    = getView();//getView is a method from DroidGap super class
WebSettings settings = myappView.getSettings();

Your are not initializing DroidGap so add super.init(); as follows:

public class MainActivity extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    super.init();//you were missing this
    WebView myappView    = getView();//getView is a method from DroidGap super class
    WebSettings settings = myappView.getSettings();
        settings.setAllowFileAccess(true); //this line throws nullPointerException for appView
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);

        super.loadUrl("file:///android_asset/www/MyHtml.html");
    }
}

You should be fine now but you can also try one (or all) of these (see WebSettings):

settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setAllowFileAccess(true);
settings.setAllowContentAccess(true);

See DroidGap.java source code.