0

I have loaded a webpage to a android webview which loads an image from its url to a webpage via javascript and it gives an error the page is not loading can anyone help?

[INFO:CONSOLE(0)] "Image from origin 'https://s-media-cache-ak0.pinimg.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.", source: file:///android_asset/demo3.html (0)

my Java code is:

    WebView wv = (WebView) vw.findViewById(R.id.help_webview);
    WebSettings webSettings = wv.getSettings();
    webSettings.setJavaScriptEnabled(true);webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    wv.loadUrl("file:///android_asset/demo3.html");

And XML is just simple web view

<WebView
    android:id="@+id/help_webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</WebView>
developer33
  • 11
  • 1
  • 6

2 Answers2

1

In general, javascript code running in a website cannot access resources from other websites. But a javascript from a website should be able to access resources from that same website. This is called same-origin policy, and is implemented by all major browsers.

Same thing also applies to android native webview same-origin-policy-and-android-webview

You can try below methods, if your file is in your local

WebView wv = (WebView) vw.findViewById(R.id.help_webview);
WebSettings webSettings = wv.getSettings();
webSettings.setAllowFileAccess(true).
webSettings.setAllowFileAccessFromFileURLs(true)   
webSettings.setAllowUniversalAccessFromFileURLs(true). 

These methods exist in API 16 and later and are false by default, but it’s probably a good idea to make sure of the defaults.

Punit Sharma
  • 2,951
  • 1
  • 17
  • 32
1

I have experienced the same error. Javascript would try to load the image, I would get the error above. After changing the method which setups the Webview settings to the code below it started to work:

private void setupSettings() {
    WebSettings settings = memoryGameView.getSettings(); // memoryGameView is an instance of android.webkit.WebView
    settings.setLoadWithOverviewMode(true);
    settings.setUseWideViewPort(true);
    settings.setJavaScriptEnabled(true);
    settings.setAllowFileAccess(true);
    settings.setAllowContentAccess(true);
    settings.setAllowFileAccessFromFileURLs(true);
    settings.setAllowUniversalAccessFromFileURLs(true);
}
gil.fernandes
  • 9,585
  • 3
  • 41
  • 57