shripalsoni04 / nativescript-webview-interface

Plugin for bi-directional communication between webView and android/ios
MIT License
89 stars 35 forks source link

Disable CORS #8

Closed ghost closed 7 years ago

ghost commented 8 years ago

Hello, i suggest to disable cross origin resource sharing limitations by default.

When you try to load local files with ajax you get a “XMLHttpRequest cannot load file:///somefile.html. Cross origin requests are only supported for protocol schemes: http, data, https.”

This seems to be the way to achieve this in native android java: http://stackoverflow.com/questions/8648616/webview-javascript-cross-domain-from-a-local-html-file

ghost commented 8 years ago

Ok, can be accomplished easy with

    webView = page.getViewById('webView');
    webView.android.getSettings().setAllowUniversalAccessFromFileURLs(true);

like pointed out in this post: http://stackoverflow.com/questions/37796808/how-to-call-setallowuniversalaccessfromfileurls-from-websettings-in-nativescript

shripalsoni04 commented 7 years ago

@einicher , Thanks for sharing the solution 👍 . As this can be done by the user in their own file, I will not prefer to set allowUniversalAccessFromFileURLs to true by default in the plugin due to security concerns.

Closing this issue as the solution is already there. Feel free to reopen if anything.

ghost commented 7 years ago

There is just one thing thats making me go crazy: inside eval()ed code xhr is suddenly returning empty results, but only when i try to fetch local files, from the web it works fine:

get = function(file) {
    console.log('get('+file+')');
    var response = null;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file, false);
    xhr.onreadystatechange = function() {
        if (this.readyState == 4) {
            response = this.responseText;
            console.log(file);
            console.log(response);
        }
    }
    xhr.send();
    return response;
}
var controller = get('controllers/main.js'); // works
eval('var content = get('views/main.html')'); //does not work, always empty
eval('var content = get('http://google.at')'); //does work

When i load my controllers with ajax i eval() them, but inside their code all xhr return empty results on local files. I am pretty serious there is a restriction in webview that prohibits xhr requests of evaled code. If anyone has any idea about this please let me know. In Firefox an Chromium the same code works fine but i think because its with http://localhost:9616/ - so no local file.

Current WebviewSettings:

    webView.android.getSettings().setAllowUniversalAccessFromFileURLs(true);
    webView.android.getSettings().setAllowFileAccessFromFileURLs(true);
    webView.android.getSettings().setLoadWithOverviewMode(true);
    webView.android.getSettings().setDatabaseEnabled(true);
    webView.android.getSettings().setDomStorageEnabled(true);
    webView.android.getSettings().setAllowFileAccess(true);