How To remove unwanted section in kotlin Webview Android Studio - javascript

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

Related

Android Webview - Change Elements with Javascript after page finished loading

I want to change some values on a HTML Page, using Javascript in a Webview.
I tried many different ways to evaluate Javscript after page finished loading.
Here is my code:
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setBlockNetworkImage(false);
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
webview.loadUrl("javascript:(function() { document.getElementById('options').value = '" + found.getId() + "'; ;})()");
button.performClick();
}
});
I think it means, that the method is called to early, before page is fully loaded.
Do you have any ideas?
in order to change value / content / styling in HTML using javascript also known as DOM Manipulate, then we have waiting after DOM ready or fully loaded. In this case, we load the page into widget WebView and then do our business.
I have a sample code that I always use in the same case,
...
final String url = "http://example.com";
final WebView webview = findViewById(R.id.my_webview);
final String myNewValue = "it works!";
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// Your custom javascript here
String myCustomJS = "document.getElementById('options').innerHTML = '" +
myNewValue + "'";
// here we execute the javascript code
webview.loadUrl("javascript:(function(){" + myCustomJS + "})()");
}
});
// and here we load the url
webview.loadUrl(url);
...
I hope the code above can help you to continue working..
Update for Waiting DOM Ready
If you have use jQuery before, then you must know
// example 1: jQuery way
$(document).ready(function() {
// place our logic here
});
// example 2: native javascript way
document.addEventListener('DOMContentLoaded', function() {
// place our logic here
});
Im use this trick to manipulate page in WebView after DOM ready (in example 2 native JS way).
Another question why not using runnable?
because we never know internet speed users, let say if we set runnable to wait 3000ms or 3sec but the web not responding after runnable execution. What happened next? users will have white blank screen and keep waiting.
hope this more clear now.
reference link: https://developer.mozilla.org/.../DOMContentLoaded_event

Auto text wrap for webview

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);

vaadin: integrate angular js using custom layout

I tried to integrate angular js application in vaadin by using custom layout like this:
VerticalLayout mainLayout = new VerticalLayout();
mainLayout.setMargin(true);
mainLayout.setWidth("1380px");
setCompositionRoot(mainLayout);
Panel panel = new Panel();
CustomLayout layout = null;
try {
String dynamicHtml = "<div ng-app=\"app\">..........</div>";
layout =
new CustomLayout(new ByteArrayInputStream(dynamicHtml.getBytes()));
} catch (IOException e) {
logger.error("could not create custom layaout", e);
}
panel.setContent(layout);
mainLayout.addComponent(panel);
importJs();
public void importJs() {
String PATH_TO_JS_SCRIPT = jsURL+"?tata=" + new Date();
String script = "try{var fileref=document.createElement('script');";
script += "fileref.setAttribute(\"type\",\"text/javascript\");";
script += "fileref.setAttribute(\"src\", \"" + PATH_TO_JS_SCRIPT +
"\");";
script += "document.getElementsByTagName(\"head
\")[0].appendChild(fileref);}catch(e){alert(e);}";
Page.getCurrent().getJavaScript().execute(script);
}
I import the script js using importJs method.
The first time i access the page, the js file is loaded and it works.
The second time, it does'nt work.
As if the script is not imported.
I don't see what is wrong in my code?
Using Javascript annotation i have the same problem.
I use
vaadin 7.6.5
java 7
Inserting angular code inside CustomLayout is bad idea.
I would recommend to read text: Vaadin and AngularJS - happy together.
There is an add-on available that lets you combine the best of Vaadin and AngularJS: Vaangular
The Js file was only included once and only once during lifecycle of the page.
To excecute this script each time we display the page i use:
if(typeof angular != 'undefined'){
angular.bootstrap(document.getElementById('swdId'), ['app']);"
}
The issue is fixed

ActiveX ok from cmd but not working in web page

I have a script to create an ActiveX component that works fine when run from the command line but reports:
SCRIPT429: Automation server can't create object
when run from JavaScript in a html page. I know the web page JavaScript works OK when I try and create a different ActiveX component like Excel.Application so I think it is something about the particular ActiveX component I am trying to create.
How can I debug this? Id there some flag I can check to see if the ActiveX component will not allow itself to be created in a web page?
The web page JavaScript looks like this:
<script language="javascript" >
function MakeOne()
{
var obj = new ActiveXObject('ECRUtilATL.Transaction');
obj.Amount1In = "12.53";
var result = "";
if (obj == null) {
result = 'null';
}
else {
result = 'not null';
}
alert(result);
}
</script>

Cancel unload window javascript without confirm

I want prevent the client leave the page in my asp.net application
whithout saving ,the folowing code get option to leave the page without saving by click 'Ok'
in the confirm.
override confirm function not work in my browser(ie8)
<script type="text/javascript">
IsSaved = false;
window.onbeforeunload = function (e) {
return IsSaved ; }
</script>
where client save the data:
IsSaved = true;
EDIT:
I want to disable click on 'ok' button too.
Thanks.
You can’t override the confirmation function, because it’s a confirmation function. If a browser wouldn’t let the user close a page just because the page didn’t want to be closed, that would be a horrible security flaw.
Confirm like everyone else. And auto-save too.
window.onbeforeunload = function() {
return !isSaved && "You have unsaved (stuff). Are you sure you want to quit?";
};
I created a library I could include in all my web sites easily, so that this functionality would be easily accessible.
Put this class in a new C# class library project, so you can reference it from your other projects (web sites).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace MyNameSpace.ConfirmLeavePageScript
{
[DefaultProperty("TextToDisplay")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ConfirmLeavePageScript : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("Are you sure you want to leave this page?")]
[Localizable(true)]
public string TextToDisplay
{
get
{
String s = (String)ViewState["TextToDisplay"];
return ((s == null) ? "Are you sure you want to leave this page?" : s);
}
set
{
ViewState["TextToDisplay"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
string script = #"
<script type='text/javascript'>
var confirmOnPageExit = function (e)
{
// If we haven't been passed the event get the window.event
e = e || window.event;
var message = '" + TextToDisplay + #"';
if(typeof ConfirmLeavePageMessage != 'undefined') //give client side the opportunity to overwrite the message instead of using message from ViewState.
{
message=ConfirmLeavePageMessage;
}
// For IE6-8 and Firefox prior to version 4
if (e)
{
e.returnValue = message;
}
// For Chrome, Safari, IE8+ and Opera 12+
return message;
};
function EnableConfirmOnPageExit()
{
// Turn it on - assign the function that returns the string
window.onbeforeunload = confirmOnPageExit;
}
function DisableConfirmOnPageExit()
{
// Turn it off - remove the function entirely
window.onbeforeunload = null;
}
</script>
";
output.Write(script);
}
}
}
You can register the tag prefix in your web site projects by putting this in your web.config. Make sure your website adds the C# class library project as a reference (put them in the same solution).
<configuration>
<system.web>
<pages>
<controls>
<add tagPrefix="tna" assembly="ConfirmLeavePage" namespace="MyNameSpace.ConfirmLeavePageScript" />
</controls>
</pages>
</system.web>
</configuration>
Then, put the control in the head of your content pages.
<head>
<tna:ConfirmLeavePageScript runat="server" TextToDisplay="Are you sure you want to leave without saving?" />
</head>
In your JavaScript functions that detect if changes have been made, call this function:
EnableConfirmOnPageExit();
You can also do the following (which I think are self explanatory):
<script type="text/javascript>
ConfirmLeavePageMessage="new message"; //set a custom message from JavaScript for the confirmation window
DisableConfirmOnPageExit(); //Disables the confirmation window (user can leave page without seeing the confirmation window)
</script>

Categories