Auto text wrap for webview - javascript

I am facing the same problem as other developers for wrapping text vertically in WebView. I already checked and tried some hints given here .
The below image is nothing but a webview with a long text(html) which is showing vertically. I want to show it horizontaly in multi lines.
I also got some clue that we can solve this by using some javascript in webview, but still not able to do it. I still don't know what and where to write javascript code and how to push it to the html/webview so it can show the text in a proper multiline format.
The question has asked multiple times but still there is no proper answer for this unfortunately.
My current code is like below:
getSettings().setJavaScriptEnabled(true);
getSettings().setDomStorageEnabled(true); // I think you will need this one
getSettings().setPluginState(PluginState.ON);
getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);// no need I think
getSettings().setLoadWithOverviewMode(true);
getSettings().setUseWideViewPort(true);
getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
And populating the data in webview something like (here descView is the WebView):
List<Element> elements = htmlObj.getElements();
if( elements.size() > 0 && elements.get(0).getHtml() != null && !elements.get(0).getHtml().equals("")) {
String htmlWrapper = null;
if(ApplicationContext.getInstance().getApplication() == null) {
htmlWrapper = CoreSettings.HTML_WRAPPER;
} else {
Application application = ApplicationContext.getInstance().getApplication();
htmlWrapper = application.getGlobalStyle().getHtmlWrapper();
}
if(htmlWrapper != null) {
descView.loadData(htmlWrapper.replace("{{content}}",WebUtils.linkifyHtml( elements.get(0).getHtml())), "text/html; charset=utf-8", "UTF-8");
} else {
descView.loadData(WebUtils.linkifyHtml( elements.get(0).getHtml()).toString(), "text/html; charset=utf-8", "UTF-8");
}
}

Use this :
Use WideViewport and Zoom out if there is no viewPort defined.
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
settings.setLayoutAlgorithm(LayoutAlgorithm.TEXT_AUTOSIZING);

Related

How To remove unwanted section in kotlin Webview Android Studio

I am converting my wordpress website in to android application using webview in kotlin, and i want to remove(hide) the header of the website in the app version, I have try so many search and i found a way to did it by injecting javascript in the
onpagefinish function, but it didnt work, this is my code with the options i have try
**val v: View = inflater.inflate(R.layout.fragment_home, container, false)
val webView = v.findViewById<View>(R.id.webview) as WebView
webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView?, url: String?) {
// the first code i try for hiding the header
// webView.loadUrl("javascript:(function() { var a= document.getElementsByTagName('menu-pusher');a[0].hidden='true';a=document.getElementsByClassName('menu-pusher');a[0].style.padding='0px';})()")
// the second code i try for hiding the header
// webView.loadUrl("javascript:if (typeof(document.getElementsByClassName('menu-pusher')[0]) != 'undefined' && document.getElementsByClassName('menu-pusher')[0] != null){document.getElementsByClassName('menu-pusher')[0].style.display = 'none';} void 0");
/* The Third Code i have try for hiding the header
webView.loadUrl("javascript:(function() { " +
"var head = document.getElementsByClassName('menu-pusher')[0].style.display='none'; " +
"})()");*/
//The Last Code i have try
webView.loadUrl("javascript:document.getElementsByClassName('menu-pusher')[0].style.display='none'");
}
}
//the webpage i am trying to load and hide the header
webView.loadUrl("https://sadeeqtech.com.ng/stech")
return v
}
}
But please guys if there is another better way to convert my wordpress website into an Android app apert from webview, please help me with it but using kotlin

Changing browser windows with window.location in javascript

I have a web site that is in two languages, English and French. now i do not know java-script, I created a code for showing different pictures using javascript depending on which language u want to use.
So if you are on the www.my-site.com/en/ you will see En_pic_ pictures same goes for the opposite.
/*These are the Popup images for the English and French portal */
var url1 = 'http://www.my-site.com/fr/';
var url2 = 'http://www.my-site.com/en/';
MagnifImage.setup(
if (window.location = 'url2'){
"En_pic_1", "/images/1.png","",
"En_pic_2", "/img/content/tracking_instructions/2.png", "",
"En_pic_3", "/img/content/tracking_instructions/3.png", "",
"En_pic_4", "/img/content/tracking_instructions/4.png", "",
}else{
"Fr_pic_1", "/img/content/tracking_instructions/1_fr.png", "",
"Fr_pic_2", "/images/mon-compte.png","",
"Fr_pic_3", "/img/content/tracking_instructions/3_fr.png","",
"Fr_pic_4", "/img/content/tracking_instructions/4_fr.png",""
}
);
Everything works but if I am on the other language page I get an alert box saying there is no Fr_pic_1 or En_pic_1.(depending on the current page I am in) The code I found to accomplish this as follows:
if( !(objRef.trigElem=document.getElementById( idParts[0] )) )
alert("There is no element with the ID:'"+idParts[0]+"'\n\nCase must match exactly\n\nElements must be located ABOVE the script initialisation.");
else
{
if(objRef.trigElem.parentNode && objRef.trigElem.parentNode.tagName=='A')
objRef.trigElem=objRef.trigElem.parentNode;
objRef.classId=idParts[1] || "MagnifImage" ;
objRef.imgObj=new Image();
objRef.imgObj.imgIndex=i;
objRef.imgObj.hasLoaded=0;
its a code I found at http://scripterlative.com?magnifimage
Please help....
You need to fix multiple things:
You must use == or === for comparison. A single = is assignment, not comparison.
You must compare to the variable name url2, not a quoted string 'url2'.
You must fix the way you pass the alternate parameters to your function MagnifImage.setup().
I switched to using window.location.href because window.location is an object and I find it better to use the actual attribute of that object you want rather than rely on an implicit conversion.
Change your code to this:
/*These are the Popup images for the English and French portal */
var url1 = 'http://www.my-site.com/fr/';
var url2 = 'http://www.my-site.com/en/';
if (window.location.href == url2) {
MagnifImage.setup("En_pic_1", "/images/1.png","",
"En_pic_2", "/img/content/tracking_instructions/2.png", "",
"En_pic_3", "/img/content/tracking_instructions/3.png", "",
"En_pic_4", "/img/content/tracking_instructions/4.png", "");
} else {
MagnifImage.setup("Fr_pic_1", "/img/content/tracking_instructions/1_fr.png", "",
"Fr_pic_2", "/images/mon-compte.png","",
"Fr_pic_3", "/img/content/tracking_instructions/3_fr.png","",
"Fr_pic_4", "/img/content/tracking_instructions/4_fr.png","");
}
Your code was likely causing many errors and thus not executing at all. You should learn how to look for javascript errors. Every browser has an error console that will show you javascript parsing or executing errors. Many browsers now have a built-in debugger than has a console in it that will also show you such information and allow you to see the exact source line causing the error. I use Chrome which has a built-in debugger which will do this. Firefox has a free add-on called Firebug that will do this.

jQuery ajax return data empty in IE

I'm using ajax to get some data then based on the data use html() to put it on the page.
In IE, the data returned is empty (it's html). It still triggers the success function, but the html is not there. I've set the dataType: "text" but still doesn't work.
Any ideas?
Thanks!
EDIT:
Here's the exact code:
$('#frm').submit(function(event){
event.preventDefault();
var self = this;
z = $('#zipcode');
if(z.val() != '' && z.val().length == 5) {
var value = z.val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
return false;
}
} else {
return false;
}
$.ajax({
url: "/ajax/zip",
type: 'GET',
async: false,
dataType: 'html',
data: {zipcode: $('.zip_field').val()},
success: function(data) {
if(data == 'false'){
error($(".zip_field"));
return false;
}else{
self.submit();
$('.container').empty().append(data);
}
}
});
})
It's submitting a zip code. On submit, it checks to make sure it's a number and 5 digits in length. If that passes, it goes to the ajax and checks to make sure it's a valid zip code (database check), if that fails it returns 'false' as text, if it's good then it returns some html.
It works in Firefox and Chrome, but not in IE. When it's good, it submits the form but the data returned alerts empty and is appended as empty space.
demo: https://so.lucafilosofi.com/jquery-ajax-return-data-empty-in-ie/
your code don't work simply because it is buggy, it have nothing to do with IE.
it should be something like below.
$('#frm').submit(function (e) {
e.preventDefault(); // this one already act as return false...
var form = $(this);
// why you have .zip_field & #zip_code ?
var zip_code = $.trim($('#zip_code').val());
var valid = (zip_code.length === 5 && !isNaN(zip_code)) ? true : false;
if (valid) {
$.get('/ajax/zip', {
zipcode: zip_code
}, function (data) {
if (data == 'false') {
alert('error!');
} else {
//if you submit the form here
//form.submit(); then the line below
//is totally useless
$('.container').html(data);
//.empty().append() is = .html()
}
});
}
});
NOTE: the fact that chrome and firefox don't display errors dosn't mean that errors are not there; internet-explorer simply tend to display errors everytime it run through malformed code etc. Also i strongly doubt that your code work really as expected since it is not so good as you may think. I guess the problem is in your code and have nothing to do with jQuery itself or it's ajax function or dataType.
One thing could be that this URL is cached by the browser. If you obtain a 304 status your response's text it will be empty. Check your HTTP cache headers, and adjust them properly. You could also trying to use POST (only GET are cached).
Also, have a look to Content-Length if is properly set.
If nothing of above works, inspect the network's call will give to you (and us) some additional details, try the IE's dev tools.
You could also try to have the same request using XMLHttpRequest's object directly (assuming you're using IE>6).
I have same problem in IE and Google Chrome
$.ajax is not working in this browser because of security reason.
so if you want to run explicitely
for chrome run chrome with
chrome.exe --disable-web-security
and in IE you need to change setting from Menu>Tools>internet Options
Some versions of IE will not ~repair~ invalid HTML in XHR requests and simply discard it; I've been bitten by this before.
Make sure the HTML returned is valid for the doctype IE thinks you're using (use the developer tools in IE to see), and check your HTML with a validator tool. Obviously, it will complain about missing <html>, <head>, etc, but ignores those and focus on the other errors. once you've fixed those, it should start working.
Also, aSeptik's answer is full of good tips to improve your code.

JavaScript: Show / Hide <DIV> based on URL string

I need to show a DIV on two pages (URL's) but not on the others.
(I have jQuery on the pages if that helps.). I'm a complete noob so all help is very much appreciate. Thank's!
Case (1) where I want to show the DIV:
On the start page, when the web browser address field reads 'www.mydomin.com'
The start page is PHP so I guess the full URL is 'www.mydomin.com/index.php'
Case (2):
'www.mydomin.com/index.php?option=com_myblog&title.html&Itemid=1&lang=en'
WHERE this part is alway the same
'www.mydomin.com/index.php?option=com_myblog&'
AND this part is always unique
'title.html&Itemid=1&lang=en
Example
if (url == 'www.mydomin.com' or 'www.mydomin.com/index.php?option=com_myblog&') {
do this
xxxxxxxx
else
nothing
This should work, if I understand the question correctly
var url = document.location.href;
if (url.indexOf('www.mydomin.com/index.php?option=com_myblog&') >= 0) {
$('#div_id').hide();
} else {
$('#div_id').show();
}
But really, if you use PHP anyway, you should figure out how to not render the div in the first place.
You can parse the query string and show/hide the div based on the result.
I also think it should be handled from PHP code instead from JavaScript. And div should not be rendered in first place.
You can target a specific query parameter of the URL using window.location.search. Using the below code, you can find an exact match anddisplay/hide the HTML element:
var firstURLParam = window.location.search.substring(1).split('&')[0];
var datGuiEle = document.getElementById("elemID");
if(firstURLParam == "debug"){
datGuiEle.style.display = "block";
}
else {
datGuiEle.style.display = "none";
}

Change query argument of jQuery suggest plugin

This question is kind-of crappy because I try to get around some limitations:
Current JS sends an ajax query with the following code
jQuery('#searchbox').suggest('/?live=1');
What the server get is the following query string:
?live=1&q=searchstring
Problem:
The server expects the query string to be preceded with 's=' not 'q='
I have to use the existing scripts so what I'm trying to so is find a way to change 'q=' to 's=' in javascript, without altering the exisiting suggest plugin or the php search script.
Thanks.
The only way you will do that is by modifying the plugin, if you want to avoid changing the script forever and need this only for one page, override the function temporarily.
$.suggest.suggest = function() {
var q = $.trim($input.val());
if (q.length >= options.minchars) {
cached = checkCache(q);
if (cached) {
displayItems(cached['items']);
} else {
//This is the line we r changing
$.get(options.source, {s: q}, function(txt) {
$results.hide();
var items = parseTxt(txt, q);
displayItems(items);
addToCache(q, items, txt.length);
});
}
} else {
$results.hide();
}
}

Categories