WebView Javascript cross domain from a local HTML file - javascript

I load a local html file (from assets folder) to the app WebView.
In the HTML I run a jQuery.getJSON(url). the url is a remote server.
This action fails, and I'm guessing because of a different origin issue (cross domain). I run the same file on chrome and there it specifically says so.
Is there a way to allow the WebView in Android to load data from remote server on a local loaded HTML file?

Today morning I found solution that seems to be working.
The Java part
Initialize your WebView:
WebView _webView = (WebView) this.findViewById(R.id.id_of_your_webview_in_layout);
get WebView settings:
WebSettings settings = _webView.getSettings();
set following settings:
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccessFromFileURLs(true); //Maybe you don't need this rule
settings.setAllowUniversalAccessFromFileURLs(true);
now you can load your your html file by standard way:
_webView.loadUrl("file:///android_asset/www/index.html");
The Javascript part
Create XHR request by standard way
var xhr = new XMLHttpRequest();
xhr.open("get", "http://google.com", false);
xhr.send();
Print the result somewhere
document.body.innerHTML = xhr.responseText
NOTICE:
This procedure works only on API level 16 or higher (At least the documentation says that).

Don't forget to add the internet permission in your manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
Also make sure you are using JSONP requests (don't forget the &callback=? as stated above)

I load a local html file (from assets folder) to the app WebView
Note that you failed to say how you are doing this. I am going to guess that it was by a loadUrl() on a file:///android_asset URL.
Is there a way to allow the WebView in Android to load data from remote server on a local loaded HTML file?
Try using loadDataWithBaseURL() to load the content, supplying a URL on the remote server as the base URL.

Ajax calls wont work from local file system. More over it will become cross-domain. So it wont work. It worked in eclipse, becuz you tried from local server.

A solution we used was to use Android to get the update files from the server, place them and overwrite files in the web folder, and then browse.

Related

Pass large blob or file from chrome extension

I try to write an extension caching some large media files used on my website so you can locally cache those files when the extension is installed:
I pass the URLs via chrome.runtime.sendMessage to the extension (works)
fetch the media file via XMLHttpRequest in the background page (works)
store the file using FileSystem API (works)
get a File object and convert it to a URL using URL.createObjectURL (works)
return the URL to the webpage (error)
Unfortunately the URL can not be used on the webpage. I get the following error:
Not allowed to load local resource: blob:chrome-extension%3A//hlcoamoijhlmhjjxxxbl/e66a4ebc-1787-47e9-aaaa-f4236b710bda
What is the best way to pass a large file object from an extension to the webpage?
You're almost there.
After creating the blob:-URL on the background page and passing it to the content script, don't forward it to the web page. Instead, retrieve the blob using XMLHttpRequest, create a new blob:-URL, then send it to the web page.
// assuming that you've got a valid blob:chrome-extension-URL...
var blobchromeextensionurlhere = 'blob:chrome-extension....';
var x = new XMLHttpRequest();
x.open('GET', blobchromeextensionurlhere);
x.responseType = 'blob';
x.onload = function() {
var url = URL.createObjectURL(x.response);
// Example: blob:http%3A//example.com/17e9d36c-f5cd-48e6-b6b9-589890de1d23
// Now pass url to the page, e.g. using postMessage
};
x.send();
If your current setup does not use content scripts, but e.g. the webRequest API to redirect request to the cached result, then another option is to use data-URIs (a File or Blob can be converted to a data-URI using <FileReader>.readAsDataURL. Data-URIs cannot be read using XMLHttpRequest, but this will be possible in future versions of Chrome (http://crbug.com/308768).
Two possibilities I can think of.
1) Employ externally_connectable.
This method is described in the docs here.
The essence of it: you can declare that such and such webpage can pass messages to your extension, and then chrome.runtime.connect and chrome.runtime.sendMessage will be exposed to the webpage.
You can then probably make the webpage open a port to your extension and use it for data. Note that only the webpage can initiate the connection.
2) Use window.PostMessage.
The method is mentioned in the docs (note the obsolete mention of window.webkitPostMessage) and described in more detail here.
You can, as far as I can tell from documentation of the method (from various places), pass any object with it, including blobs.

Import XML with jQuery: works on server, not locally

I'm working on a script that reads an XML file and then outputs the data. It works perfectly when it runs on my web server, but won't run from my local machine. (The "542Data.xml" file is stored in the same folder as the HTML page on both the server and my computer, and I checked that all file versions are the same. I've tried it in Firefox and Chrome with the same results.)
<div id="output"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "542Data.xml",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml)
{
$(xml).find("point").each(function(index)
{
$("#output").append("Name: " + $(this).attr("name") + "<br />");
});
}
</script>
The XML is structured as:
<?xml version="1.0"?>
<destinations>
<point name="Tot Lot at Bryan Park">
<lat>39.15611</lat>
<long>-86.52664</long>
<type>outdoors</type>
</point>
<point name="Playground at Cascades Park">
<lat>39.19633</lat>
<long>-86.53581</long>
<type>outdoors</type>
</point>
</destinations>
What do I need to change to get this working locally?
EDIT: I was wrong, it's working in Firefox. (embarrassed!)
Your script works fine for me in Firefox.
Chrome has some security feature that disallows what you wanted to do (using file:/// for AJAX requests). You need to start your browser with:
chrome --disable-web-security
to disable security checks. (--allow-file-access-from-files might also do the trick, but I haven't tested it yet)
Warning: disabling security checks affects your browser security and should only be used for temporary development purposes. If you plan to run the code from your local machine in a prolonged period of time, consider installing a web server on your local machine.
If by "working locally" you mean you have the html and xml file in a folder and open the HTML file by double clicking on it, then there is no way.
In order for it to work locally you need an web server which will resolve http requests. Opening a local file on a file system is not what is happening here. .ajax() is making a server request. Without a server it won't work.
What are you using to develop? Check if the development server you are using can serve XML files.
According to the given (small) info. There is may be a security reason i.e. importing jquery from google's repository. Please give more code or look at the error console in firefox - ctr+shift+j and copy paste the error if there is any, or just download jquery and include it with path in local location.
It is running on server but not on your machine. See, the ajax request needs a local server running. To make it work, start some local server on your machine. For example, if you're on Windows, then download WAMP, and if on Linux, then install LAMP. Put your files in www folder. Then start the local server..and then access your file using localhost/your_file_name. That'll give you the result as you want it.

Issue in cross domain call with require.js?

I want to load an HTML div from an html file hosted on windows azure blob (own by me) into a MVC view which is also hosted on windows azure web role ( Both the blob and the web role are owned by me ).
I tried using jquery.load() but it runs into cross domain issues and window azure blobs do not allow changing the CORS policy. Next i am trying to use Require.Js and Text.Js to achieve this cross domain load.
From the Text.Js documentation :
Text plugin determines that the request for the resource is on another domain, it will try to access a ".js" version of the resource by using a script tag. Script tag GET requests are allowed across domains. The .js version of the resource should just be a script with a define() call in it that returns a string for the module value.
My js code for cross domain call with require.js is :
require(["text!http://xxxxx.blob.core.windows.net/xxx/File"],
function (html) {
alert(html);
}
);
Now the issue which i am facing is that the File's .js version was successfully loaded by the plugin (Confirmed by using chrome inspector) but in the callback when i tried to access the text content of the file , it show me undefined. What i am doing wrong here, why the callback does not have the text content? Can anybody help me to solve this issue ? In case this is not solvable, i am open to other ways to achieve this cross domain load.
My understanding from require.js documentation is that cross domain calls can be accomplished by call a javascript version of the resource.
Try with define:
define(["text!http://xxxxx.blob.core.windows.net/xxx/File"], function (html) {
return {
template: html;
}:
}
);

Xml to js code problem

So i'm very new to xml to javascript so i thought I would learn from w3schools, but this site
http://www.w3schools.com/xml/xml_to_html.asp shows an example that I can't mimic locally. I copy/pasted the .js and downloaded the xml but I just get a blank screen!
It's working in there try it yourself but not for me? Do I need it on a server or something?
Yes, that code retrieves the XML data from a web server using AJAX. Since you don't have a server running locally, you can change the URL to point directly to the w3school's version:
xmlhttp.open("GET","http://www.w3schools.com/xml/cd_catalog.xml",false);
Alternatively, play around on their online version ;)
well i guess you have to add the example xml (cd_catalog.xml) to your file system. and you definitively have to access the html file on a server (apache i.e.)
First, ensure that both HTML file (with the Javascript block in it) and XML file are placed in the same directory.
Next, you probably need to place those files under your local web-server and open the HTML like this:
http://[local server host]/ajax.html
instead of opening the file directly from e.g. Windows Explorer:
C:\[path to the file]\ajax.html
For the latter case you'll get an "Access is denied" error.
-- Pavel
Are you running this under a web server or just creating a couple of text files and loading them in your browser?
The "GET" request this relies upon could possibly be failing.
Use Apache or another similar HTTP server and run the example as if it were hosted on the web.

Ajax Parsing Local XML

I'm building a local html file to show dynamically some data from an XML file and by using Chrome's Inspector I figured my XML file is not being parsed because it is "not hosted on a webserver"
XMLHttpRequest cannot load data.xml. Cross origin requests are only supported for HTTP.
I know that there are a few flags I could pass to Chrome/web browser to workaround this limitation but I'm looking into some alternative method. I will probably have to distribute this files to a few people and teaching them how to pass flags to the browser is not an option for me. Hosting them on a web server is not an option either.
Thanks a lot in advance.
No ghost unless you set up a local server or host the XML file locally. Ajax has to follow the same origin policy.
If you're willing to use a library you can use jQuery's AJAX method to perform a cross-domain request (i'm not entirely certain that jQuery will support what you're trying to do). JSONP works, but you have XML data...
You could try loading it in a script tag anyway and see if you can get the innerHTML value without breaking the script; once you're done getting the text from it, remove the script from the page. You may be able to get at the data before the browser tries to parse the script by attaching onload and onreadystatechange events to the script element.
var s = document.createElement('script');
s.src = '/path/to/file.xml';
s.onload = s.onreadystatechange = getData;
function getData(e)
{
//get the text out of the script element
//remove the event handler from the script element
//remove the script from the page
}
document.getElementsByTagName('body')[0].appendChild(s);
I didn't test it, but it might work.
How about setting up a local webserver? XAMPP should be easy to install even for novice. Just tell them to put your files in the htdocs folder, run xampp and start the apache server.
Unless there's a compelling reason to have a separate html and xml file, you could just put the data directly in the html file.
I'm afraid if chrome only provides options that you don't like to apply, your application and chrome will not come together. Access via iframe & object does'nt work too, load()-method of createDocument is not supported by chrome(if it does I guess you got the same error).
Whatever you try will be a sideway to pass chrome's restrictions, what cannot be good, because I think they have good reasons to setup these restrictions.

Categories

Resources