Load HTML file into WebView that contain external js script - javascript

I want to load a html code into a webview. But the html code has several other external resources. for example in the html code I have :
<script type="text/javascript" src="//cdn3.example.com/example.js"></script>
but it seems that 'example.js' is not executed when rendering the webview.
Is it possible to achieve that ? Thank you

I have similar issue, webview loaded from file:// and won't load external resources... cors set to * on the server side too.
So digging into it further, seems my problem was I used custom ssl certs on server side and android couldn't verify the server authenticity, and so requests were being cancelled. (adding intermediate certs to app would help)
alternately
You can override webclient's shouldInterceptRequest and fetch the external scripts yourself, returning the request from which webview will draw data (make sure you don't fetch during the shouldInterceptRequest call or it will be slooooooow sequentially fetching resources; instead, return a request's subclass and start fetching data async, so by time call to getData comes you already have what you need... search so for async shouldInterceptRequest for help with that).

Related

JavaScript - cross origin request blocked - non-server solution

I'm a desktop developer that is trying to learn some web basics on the side. I've previously put together an asp.net mvc website that worked more or less okay and am currently working on a simpler, html/css/js only website.
A number of the pages on the website will contain images, with a number of pieces of data accompanying them, so I thought I'd put together a JSON with all of the data, including the links to the images and generate the image list on page load. The problem that I ran into is the JavaScript cross origin request when trying to fetch the JSON file.
I've looked around at solutions and most of them recommend spinning up a server - either asp.net or node.js to fetch the JSON from. Couple of questions:
If I can write HTML that references image files, why can I not fetch a json from javascript? Is there a fundamental piece of understanding that I'm missing here?
Is there any other way of using a JSON without spinning up a web server? Should I try embedding it into the HTML? Is that a bad idea?
Any other pointers/links to resources with relevant info :)
// My JavaScript:
<script>
$(document).ready(function(){
buildGallery('test.json', '#gallery');
});
// Builds a collection of thumbnails from the json specified inside of specified div
function buildGallery(jsonUrl, galleryDiv){
$.getJSON(jsonUrl, function(data){
// Ensure the data is in correct format
if (typeof(data) !== 'object'){
return;
}
// Build the gallery
$.each(data['images'], function(key, image){
var thumbnail = '<img src="' + image['url'] + '"/>'
$(galleryDiv).append(thumbnail);
});
});
}
</script>
This is based of: https://api.jquery.com/jQuery.getJSON/
Thanks heaps!
There are a couple issues with what you are trying to accomplish with the provided code.
First, you are trying to make an Ajax request to a resource that is not hosted on an http server. Ajax is a wrapper for XMLHttpRequest which was designed for fetching resources using the http protocol. However, it can support other protocols such as file, and ftp.
Second, CORS is not controlled by the browser, it's controlled by the http server. Cross domain origin requests can work, but only if the resource you are requesting responds with an http header that allows your domain to access it. Since the resource you are requesting has nothing to do with http, it will probably throw an error.
So why do images work using the file:// scheme? The <img/> tag supports loading resources using any scheme your browser cares to support. It turns out most browsers support it.
So I can't get json into my app without an http server!#? Yes and no. No because you usually cannot request a resource not served through an http server using XMLHttpRequest. However, you can still request resources through other means.
I recommend using the File API for reading files from the users filesystem.

Make an iframe (or similar) load its content through a websocket proxy?

I would like to display a existing sub-site in an iframe.
The twist is that I would like the content to be served via a custom Websocket http proxy. The server-side of the Websocket would handle retrieving the original sub-site content via http from the origin server.
I assume that all iframe browser (and Ajax) resource loading calls would need to be intercepted and satisfied by some Javascript code, which would get the needed resources via a Websocket connection.
Is this plain impossible?
When I got your problem correctly you try to get a web document and remove all the <iframe>-Tags.
You can do this by getting reading the page by file_get_contents() and removing all <iframe>-Tags by its pattern using preg_replace()
<?php
$content = file_get_contents('http://www.w3schools.com/html/html_iframe.asp');
echo preg_replace('/<iframe(|\/)(?!\?).*?(|\/)>/','', $content);
?>
Note: As some requests without a base URL (for example <img src="...) will look the for the resources on your server the site will not render correctly.
dran you stackoverflow! one day i will know your formitting... :x

Prevent html pages from browsing caching

The problem I am having is partial files(*.html) are getting cached by browser. While developing it's not a big problem but once I deploy the application, clients see the old page(s) until they clear their cache or hit ctrl F5
I have tried specifying meta tags(CACHE-CONTROL,EXPIRES) but still see those pages getting picked up
from cache in the developer tool of chrome (Maybe I am missing something here?).
I was going to try and add some random number in front of the url like
<div ng-include src="'views/test.html?i=1000'"></div>
But came across https://groups.google.com/forum/#!topic/angular/9gORRowzP2M ,where James cook rightly states that this way would fill cache with partials over and over.
I read somewhere that it's better to set the meta tags in headers from the server but I don't know how to do that? I was thinking of somehow doing it in an http interceptor?Maybe somehow add meta tags in request or response of this httpinterceptor? https://gist.github.com/gnomeontherun/5678505
Any ideas how to do that? Or if it's good/bad idea? Or any other way to prevent partial pages getting cached by browser?
To prevent caching it is in many circumstances not possible to completely turn it off from the client side only. You have to configure your server in the right way so that it produces the right HTTP-Headers.
But with the help of $templateCache you can move your html partials form single files into script tags in your index.html file. This will also reduce the number of AJAX calls your app needs to make.
With the templates in your index.html you only need to make sure that the index.html is not getting cached.
Here is also a discussion of it:
Is there a way to make AngularJS load partials in the beginning and not at when needed?
In case anyone else run into the same problem, I ended up adding an httphandler and added the "Cache-Control" and "Expires" in the response header
public void ProcessRequest(HttpContext context)
{
var partial = context.Request.FilePath;
var filepath = context.Server.MapPath("~/" + partial);
context.Response.AddHeader("Content-Disposition", "filename=\"" + Path.GetFileName(filepath) + "\"");
// To make sure partial html pages are not cached by browser(s)
context.Response.AddHeader("Cache-Control", "No-Cache");
context.Response.AddHeader("Expires", "0");
context.Response.ContentType = MimeTypesHelper.GetMimeType(filepath);
context.Response.WriteFile(filepath);
}

Javascript detect which host it was loaded from

I have a Javascript library I'm working on. It can be self-hosted or run from another server. The script makes a number of AJAX calls and the preferred method is making POST requests to the same host as the including page. To allow for cross-domain calls it also supports JSONP, but this limits the amount of data that can be sent (~2K to safely accommodate most modern browsers' URL length limits).
Obviously the user including the script knows where they're getting it from and could manually select JSONP as needed, but in the interest of simplifying things, I'd like to detect, within the script itself, whether the script was loaded from the same host as the page including it or not.
I'm able to grab the script element with jQuery but doing a $('script').attr('src') is only returning a relative path (e.g. "/js/my-script.js" not "http://hostname.com/js/my-script.js") even when it's being loaded from a different host.
Is this possible and if so, how would I go about it?
Thanks in advance.
Don't use JSONP, use CORS headers.
But if you really want to do JS check, use var t = $('script')[0].outerHTML.
Effect on my page:
[20:43:34.865] "<script src="http://www.google-analytics.com/ga.js" async="" type="text/javascript"></script>"
Checking location.host should do the trick.

Unable to load xml file in javascript running site under Development Server

I am unable to load an xml file in javascript (using the same code as here) when running the site under the VS Development Server. It works when running under IIS. I know that IIS displays static content without authorization by default and DevServer does not. I've tried putting the file in different places under the web app project (a custom Common directory, App_Data, the root) without success.
The error gets caught by the Application_Error method in global.asax and it says
"System.Web.HttpException (0x80004005): Path 'foo.xml' is forbidden."
However, the ajax call does not crash and when done using a different piece of code (the jQuery.ajax() method) the ajax call is always succesfull and never goes into the error callback I provide.
The script is called from a script block on an aspx page.

Categories