Javascript does not work in WebView below Android 4.4.4 - javascript

I am trying to load a local js file from the assets folder in a web view.
It works perfectly under Android 4.4.4 and Android 5 but not under Android 4.3 and lower versions.
The css is displayed correctly but the js does not seem to be loaded.
This is my code:
private static final String HTML_CHARSET = "<meta charset='utf-8'>";
private static final String HTML_TITLE = "<title>Aufbau einer Tabelle</title>";
private static final String HTML_STYLESHEET = "<link href='matrix.css' type='text/css' rel='stylesheet'/>";
private static final String HTML_SCRIPT1 = "<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js' type='text/javascript'></script>";
private static final String HTML_SCRIPT2 = "<script src='https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js' type='text/javascript'></script>";
private static final String HTML_SCRIPT3 = "<script src='matrix.js' type='text/javascript'></script>";
private static final String HTML_VIEWPORT = "<meta name='viewport' content='width=device-width, initial-scale=1.0'>";
private static final String HTML_STRING = "<!doctype html> <html> <head> " + HTML_CHARSET + HTML_TITLE + HTML_STYLESHEET + HTML_SCRIPT1 + HTML_SCRIPT2 + HTML_SCRIPT3 + HTML_VIEWPORT + "</head> <body> <table> %s%s </table> </body> </html>";
...
String htmlString = String.format(HTML_STRING, htmlTableHeader, tableBody);
WebSettings settings = matrixWebView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setDomStorageEnabled(true);
matrixWebView.loadDataWithBaseURL("file:///android_asset/", htmlString, "text/html", "UTF-8", null);
Anyone has an idea?

loadDataWithBaseURL doesn't need to be prefixed with "file://" or the path. It needs just the HTML content.
loadURL can be used to load a file contents.

Related

How to Pass Variables to Javascript from C# using Invoke?

private void WebBrowser_Clicked(object sender, RoutedEventArgs e)
{
wb.Navigate("C:/Users/intern3/source/repos/MarketingProject/Samples/WPF/RESTToolkitTestApp/index.htm");
wb.InvokeScript("SetCoords", new object[] { coord1, coord2 });
}
wb is a WebBrowser object
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" http-equiv="X-UA-Compatible" content="IE=edge" />
<script type='text/javascript' src='http://www.bing.com/api/maps/mapcontrol?callback=GetMap&key=AgCKDO35_SFD68BDTuy_QuFz48T2P3FmYQKttx8y2DXQNR-ufCeae5riWUYmPCmk' async defer></script>
<script type='text/javascript'>
var map;
var lattitude = 34.2;
var longitude = -117.8;
function SetCoords(lat, long) {
lattitude = lat;
longitude = long;
}
...
I've tried adding the coordinates to the end of the url as a querystring but since it's a local file I don't think it's possible. If it is please let me know because that would be an easy solution to this too. But otherwise, this is giving me this error:
System.Runtime.InteropServices.COMException: 'Unknown name. (Exception from HRESULT: 0x80020006 (DISP_E_UNKNOWNNAME))'
It takes some time until the WebBrowser control has loaded the page so that it knows the Javascript function. Instead of calling the function directly after the load, use a handler for the LoadCompleted event to run the function, e.g.:
public MyForm() // This is the constructor of your form/page
{
InitializeComponent();
wb.LoadCompleted += WebBrowser_LoadCompleted;
}
private void WebBrowser_Clicked(object sender, RoutedEventArgs e)
{
wb.Navigate("C:/Users/intern3/source/repos/MarketingProject/Samples/WPF/RESTToolkitTestApp/index.htm");
}
private void WebBrowser_LoadCompleted(object sender, NavigationEventArgs e)
{
wb.InvokeScript("SetCoords", new object[] { coord1, coord2 });
}
Above code adds the handler for LoadCompleted manually, but you can also add it in the designer.

LinkedIn Learning LTI failed authentication

I'm attempting to integrate LinkedIn Learning Single-Sign-On via an LTI connection, however I'm always faced with the response: LTI_FAILED_AUTHENTICATION.
LinkedIn Learning - LTI_FAILED_AUTHENTICATION
When I test it out on the Saltire test platform, it strangely works.
The parameters match what I am sending from the code below:
Saltire LTI Success authentication
Have tried copying over the the values of oauth_nonce, timestamp and oauth_signature from Saltire to my page, and that worked also, which scores out the possibility of domain whitelisting requirement.
LinkedIn support have come back saying there seems to be something wrong with the generated signature, but I'm not sure what is wrong about it, since that is generated by the parameters passed.
Is there something incorrectly setup from my page which I am not seeing?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex" />
<title>Access LinkedIn Learning</title>
<script src="bundle.js"></script>
</head>
<body>
<form id="id_frmConnect" name="frmConnect" enctype="application/x-www-form-urlencoded">
</form>
<script>
var oauth = require('oauth-sign');
var action = 'https://www.linkedin.com/checkpoint/enterprise/login/[accountID]?application=learning&redirect=https://www.linkedin.com/learning/me';
var method = 'POST';
var consumer_key = '************';
var consumer_secret = '************';
var timestamp = Math.round(Date.now() / 1000);
var params = {
lti_message_type: 'basic-lti-launch-request',
lti_version: 'LTI-1p0',
oauth_callback: 'about:blank',
oauth_consumer_key: consumer_key,
oauth_nonce: btoa(timestamp),
oauth_signature_method: 'HMAC-SHA1',
oauth_timestamp: timestamp,
oauth_version: '1.0',
user_id: 'S495696'
};
var signature = oauth.hmacsign(method, action, params, consumer_secret);
params.oauth_signature = signature;
var form = document.querySelector("#id_frmConnect");
form.action = action;
form.method = method;
for (var name in params) {
var node = document.createElement("input");
node.type = 'hidden';
node.name = name;
node.value = params[name];
form.appendChild(node);
}
</script>
</body>
</html>
I figured out the issue. By using the Saltire test tool, I was able to verify that my signature was generated correctly when using their testing URL: https://lti.tools/saltire/tp
You can play with an example here: https://learningcom.github.io/ltitest/index.html
So after looking at the LinkedIn URL, I discovered that the signature was getting generated with an unnecessary long URL which contained parameters.
Removed: ?application=learning&redirect=https://www.linkedin.com/learning/me
Therefore, I shortened the URL to:
var action = 'https://www.linkedin.com/checkpoint/enterprise/login/[accountID]';
No more errors!

How to crawl web page which run Javascript with cookies check before showing main content

I'm trying to crawl and parse following RSS feed:
http://english.alarabiya.net/.mrss/en/sports.xml
When I open it in browser it gives me the normal RSS feed that I want to parse. But when I download it inside Java it shows me the following:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function getCookie(c_name) { // Local function for getting a cookie value
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start!=-1) {
c_start=c_start + c_name.length + 1;
c_end=document.cookie.indexOf(";", c_start);
if (c_end==-1)
c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function setCookie(c_name, value, expiredays) { // Local function for setting a value of a cookie
var exdate = new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/";
}
function getHostUri() {
var loc = document.location;
return loc.toString();
}
setCookie('YPF8827340282Jdskjhfiw_928937459182JAX666', '105.183.123.12', 10);
try {
location.reload(true);
} catch (err1) {
try {
location.reload();
} catch (err2) {
location.href = getHostUri();
}
}
</script>
</head>
<body>
<noscript>This site requires JavaScript and Cookies to be enabled. Please change your browser settings or upgrade your browser.</noscript>
</body>
</html>
I'm using simple stream reading, here is my code:
try {
URL url = new URL("http://english.alarabiya.net/.mrss/en/sports.xml");
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Is there anyone know how to parse the main RSS content and bypass the Javascript part with cookies? Or any ideas?
P.S.: I'm using Rome library to crawl the RSS feed, but I think the problem out of its scope.
Try HtmlUnit library and use setJavascriptEnabled(true) there
Your question is simillar with this one

Can't load CSS/JS on javafx Webview

I am having trouble getting css/js to show up on a Webview.
Here is what I am doing:
initializing the webview and engine
WebView browser = new WebView();
WebEngine webEngine = browser.getEngine();
webEngine.setJavaScriptEnabled(true);
This is where I load html content:
htmlViewImgBtn.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEven
#Override
public void handle(MouseEvent event){
if (counter == 0){
contentContainer.getChildren().addAll(browser);
webEngine.loadContent(export.getHTML(note));
//browser.getEngine().load("http://stackoverflow.com/questions/34554583/cant-load-css-js-on-javafx-webview");
contentContainer.getChildren().remove(noteContent);
counter = 1;
}
else {
contentContainer.getChildren().remove(browser);
contentContainer.getChildren().addAll(noteContent);
counter = 0;
}
}
});
Note: The commented code works when loading a website onto the webview, no issues. But Still does not work for the content I am loading.
The content (HTML) that is loaded looks looks like this:
<link href="prism.css" rel="stylesheet" type="text/css" />
<script src="prism.js" type="text/javascript"></script>
<pre><code class="language-java">System.out.println("Hello");
</code></pre>
Also, the css and js files are in the same directory as the java file
I can confirm that the html works by loading it on a web browser, What am I missing?
Blockquote
I was able to get it working by modifying the html as such:
"<link href=\"" + getClass().getResource("./prism.css") + "\"" + " rel=\"stylesheet\"" + " type=\"text/css\"" + " />\n" +
"<script src=\"" + getClass().getResource("./prism.js") + "\"" + " type=\"text/javascript\"" + "></script>\n" +
(rest of html);
You can use ResourceLoader to load HTML, js and css which are located in the same directory as the Java class.
URL url = getClass().getResource("index.html");
webEngine.load(url.toExternalForm());

How to show json data into html <ul><li></li></ul> tag using jquery in asp.net

I am working on asp.net application where i am trying to fetch data from database in JSON format and display that JSON data into html-ul-li tag using jquery. My Html Page is:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script language="javascript" type="text/javascript">
//function GetCompanies() {
$(document).ready(function () {
$.ajax({
type: "POST",
url: "MobileServices.asmx/BindCategory",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: true,
success: OnSuccess,
error: OnError
});
function OnSuccess(data) {
$.each(data, function (key, value{
$("#ulCategory").append("<li><a rel=external href=Category_News.html?ID=" + value.Category_ID + ">" + value.Category_Name + "</li>");
})
}
function OnError(data) {
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ul id="ulCategory">
</ul>
</div>
</form>
</body>
</html>
My WebService to Access the Data is :
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
using Newtonsoft.Json;
using System.Configuration;
namespace MobileNewsAppication
{
/// <summary>
/// Summary description for MobileServices
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MobileServices : System.Web.Services.WebService
{
public class NewsCategory
{
public long Category_ID { get; set; }
public string Category_Name { get; set; }
public string QFlag { get; set; }
}
[WebMethod]
public string BindAllCategory()
{
DataTable dt = new DataTable();
//List<NewsCategory> details = new List<NewsCategory>();
using (SqlConnection con = new SqlConnection(Connection))
{
SqlCommand cmd = new SqlCommand("AllCategory_Select", con);
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return JsonConvert.SerializeObject(dt);
}
}
}
}
But the the ul Tag is not binding any list item inside. I think foreach loop defined inside jquery OnSuccess method may be wrong. Please help me.
If this isn't a typo here then it's a syntax error causing the success callback to fail...
function OnSuccess(data) {
// $.each(data, function (key, value{ <- this is wrong
$.each(data, function() {
$("#ulCategory").append("<li><a rel='external' href='Category_News.html?ID=" + this.Category_ID + "'>" + this.Category_Name + "</li>");
});
}
Try using this inside each instead. I also wrapped the link attributes in quotes. Other than that it looks fine to me. If that isn't the issue then put console.log(data); as the 1st line of the success callback and check the console for that and any errors.

Categories