Can i get data inside web browser from android sharedpreferences? - javascript

I am developing an application for android in which I storing some data to shared preferences.
Now My question is can i fetch that data inside a web browser on same device??
For example:
when i run my application
I have stored something like this :
Key :User_Email
Value:abc#abc.com
and then close the application.
Now i am on android web browser and open my webpage on which i have added a button,On Clicking this Button I am trying to get that value from shared preferences.
Please help me...

Internet and android application are different things.
You can't do this directly, due to security reasons.

You can use the below example code:
String html = sharedPref.getString("KEY");
String mime = "text/html";
String encoding = "UTF-8";
webview.loadDataWithBaseURL(null, html, mime, encoding, null);

Related

Access DOM content of browser within Android runtime

Say we have a standard login page like the one below:
We can access the HTML elements in the DOM using jQuery or plain JavaScript like this:
In other words, the way to get the pixel location of an element in a web page is quite simply by using element.getBoundingClientRect():
var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);
So we can do this from the console or programmatically from a web app.
Now, say we have an Android browser (Chrome/Mozilla/WebView) in the foreground at any time. I can retrieve the URL of the web page in the browser. In this case:
https://login.microsoftonline.com/
So my question is, given the URL of a login page, how do I similarly get access to the same input field on an Android browser?
I need to be able to access the HTML elements of a web page in an Android browser, and calculate its pixel location. As input, I have the URL of a web page in any Android browser.
I am talking about doing this from an Android app, within the Android runtime, i.e. programmatically using Java/JS code.
In case someone needs the DOM structure of the page as text, it can be obtained programmatically with the following (Java) code:
URL url;
HttpURLConnection urlConnection;
String DOMContent = null;
try {
url = new URL("https://login.microsoftonline.com/");
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
DOMContent = readStream(urlConnection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I need access to the HTML elements of a mobile web page within the Android runtime, just as we would in a web app or extension in a desktop browser. Or in other words, I need to be able to access/manipulate the DOM content of a mobile browser from an Android app.
How can this be done?
Update:
JavaScriptBridge looks promising. DocumentBuilder could help us convert the DOM into Java objects which may then be accessed/manipulated natively from Android.
References:
1. How to execute JavaScript on Android?
2. Calling JavaScript functions in WebView
3. How to run Javascript code in a background Service on Android
4. Is there any way to get access to DOM structure in Android's WebView?
5. Android webview Access the DOM
6. In Android Webview, am I able to modify a webpage's DOM?
7. Android WebViews and the JavaScript to Java bridge
8. Using Javascript bridge in android
9. Alternative way for communication between WebView and native
Use the following code after the page has been loaded (implement a custom WebViewClient and check the onPageFinished)
String query = "document.getElementById(\"WhateverElement\").getBoundingClientRect();"
webView.evaluateJavascript(query, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.d("LogName", s); // s has the getBoundingClientRect
}
});
The webpage needs to be rendered first in order to get the pixel position of the input field. and to manipulate dom content in android, the best way is to go with JS Interface. The way mentioned by ZUN is also helpful. You can execute arbitrary JavaScript at runtime either way.
However, there is one particular library that can catch your attention i.e. jsoup
From the jsoup website:
jsoup is a Java library for working with real-world HTML. It provides
a very convenient API for extracting and manipulating data, using the
best of DOM, CSS, and jquery-like methods. jsoup implements the WHATWG HTML5 specification and parses HTML to the same DOM as modern browsers do.
Side note: if you don't want to show webpage to the user till all of your calculations are done, you might be interested in playing with Visibility of WebView

Automation server can't create object: ActiveXObject creation error

I have a very simple javascript code in oracle procedure which us used for fetching the Username for Active Directory as my application don't have any user interface.
htp.p('function disp_alert()');
htp.p('{');
htp.p('var WinNetwork = new ActiveXObject("WScript.Network")');
htp.p(' WinNetwork = WinNetwork.UserName');
htp.p('alert(WinNetwork)');
htp.p('}');
It throws exception ActiveXObject creation error: Automation server can't create object
I tried changing browser setting script ActiveX controls marked safe for scripting to enable and it worked.
But in my case the application is accessed by users in client network and we can't tweak security settings for each machine in network. Can anyone suggest an alternative solution or any other method for fetching the windows username?
If you absolutely have to use WScript.Shell for whatever you want to accomplish, you may set the option for your intranet zone by GPO.
You may find the corresponding GPO setting with the help of that site: https://getadmx.com/?Category=InternetExplorer&Policy=Microsoft.Policies.InternetExplorer::IZ_PolicyScriptActiveXMarkedSafe_3

Javascript Access to File on local machine

I want to open the files located on local drive using window.open().
When i try to access the file using window.open i am getting error "Access is denied."
Would somebody help to achieve this requirement in Internet explorer 8.0?
Thanks!
You can't. And thank God for that. Imagine how insecure the internet would've been if JS was able to access a client's file-system.
Of course, IE8 has the MS specific JScript superset (ActiveXObject), which does enable filesystem access:
var fileHandle,
fs = new ActiveXObject("Scripting.FileSystemObject");
fileHandle = fs.OpenTextFile("C:\\path\\to\\file.tmp", 1, true);
fileHandle.Write('This is written to a file');
console.log(fileHandle.ReadLine());//will log what we've just written to the file
But this is non-standard, is - I think- no longer supported either, and doesn't work X-browser.
Here's the documentation. At the bottom there's a link to a more detailed overview of the properties and methods this object has to offer, as you can see, there's a lot to choose from
I'm adding this answer just to be complete, but so far as Web Pages go, Elias Van Ootegem's answer is correct: you can't (and shouldn't be able to) get to the local hard drive.
But .. you can isf your page is an HTA (HTML Application) :
HTML Application wiki
This is essentially a web page with .hta as the extension(usually) and some extra tags to tell IE that it's an HTA application, not a web page.
This is something that runs via the windows operating system and is so far as I'm aware only available for IE. The HTA application opens as a web page in IE, but without the usual web navigation / favourites toolbars etc.
Note that if you have a page on an internet server delivered as an HTA application, you're likely to cause virus scanners and firewalls to pop up because this would essenstially be running a script whcih could do manything to your computer. Not good for general internert stuff at all, but might be useful in a secure environment like an intranet where the source of the application is known to be safe.
To get to the file system, you can use javascript code like this :
// set up a Fils System Object variable..
var FSO = new ActiveXObject("Scripting.FileSystemObject");
// function to read a file
function ReadFile(sFile) {
var f, ts;
var s="";
if(FSO.FileExists(sFile))
{
f = FSO.GetFile(sFile);
ts = f.OpenAsTextStream(ForReading, TristateUseDefault);
if (!ts.AtEndOfStream) {s = ts.ReadAll( )};
ts.Close( );
}
return s;
}
alert(ReadFile("c:\\somefilename.txt");

Programmatically open new browser tab with Silverlight and set content

Was wondering if there is any way in Silverlight to open a new browser tab and set its content. In short, my app receives files (binary data) and needed to have the user's browser presenting them.
My app downloads contents (images/pdfs/whatever) from repositories from the cloud and stores them as binary data in a local cache; then after that I need a way to display those now local contents to the end user in a new tab. The "new tab" requirement is due to silverlight not supporting rendering of many file types such as .gif, .pdf and others - things that browsers handle easily, either natively or with widely used plugins. So my current WTF-y solution uses System.Windows.Browser and consists in the following:
// Get document and body
var doc = HtmlPage.Document;
var body = doc.Body;
// Create a <form> element and add it to the body
var newForm = doc.CreateElement("form");
newForm.SetAttribute("action", "www.example.com/contentpresenter.php");
newForm.SetAttribute("enctype", "multipart/form-data");
newForm.SetAttribute("method", "POST");
newForm.SetAttribute("target", "_blank");
body.AppendChild(newForm);
var inp = doc.CreateElement("input");
inp.SetAttribute("type", "text");
inp.SetAttribute("name", "mcontent");
inp.SetAttribute("value", Tools.ToBase64( content.Content as Stream ));
newForm.AppendChild(inp);
var inpt = doc.CreateElement("input");
inpt.SetAttribute("type", "text");
inpt.SetAttribute("name", "tcontent");
inpt.SetAttribute("value", content.ContentType);
newForm.AppendChild(inpt);
// Send away!
newForm.Invoke("submit");
In short, it creates a javascript script that posts the content to a remote PHP script which in turn does nothing more than decoding and presenting the content, which will open in a new tab. Yes, I'm fully aware of how idiotic it sounds - but does the trick and works as intended.
As far as I know, creating a new HtmlWindow and building up/altering its contents is not an option due to security constraints. An obvious option is having Silverlight produce javascript which would in turn create a new tab that loads the provided content, but javascript is not too big in handling binary or base64 data - at least not cross-browser seamlessly - and the whole thing seems stupid anyways.
Is there a solution to achieve this solely through Silverlight, or at least with a minimum amount of javascript involved? Alternatively, is there any javascript library you would recommend to handle base64 data?
Best regards!
I recomend you to find Telerik's silverlight components sources and use RadHtmlPlaceholder (slightly buggy).
+ You can enable trusted application to run inside the browser for SL 5 and use WebBrowser control (best quality) but for windows only.

Detect if javascript is enabled in a winforms/mfc embedded browser

I have a native (windows) application that has an embedded web browser. Currently I'm invoking a javascript function from the backend (c++/c#). However, if javascript is disabled this fails and I'd like to provide a fallback mechanism. Is there a way to determine if javascript is disabled?
In the IE Web Control, you can simply force JavaScript on. Please refer to the following interfaces, which your host has to implement:
IDocHostUIHandler
IDocHostShowUI
IInternetSecurityManager
IServiceProvider
Another approach would be for your HTML page to query the window.external object and call a method on it, which you implement in your host, which sets a flag to true. Not being called would mean the JavaScript was not executed.
Wow, using web browser under mfc is really pain in the ass, you can do it by getting the IInternetSecurityManager, and check if is enabled to execute javascript by current policy, if user select to disable javascript on his IE, you will need to overwrite the value in the registry.
HRESULT hr = CoCreateInstance(CLSID_InternetSecurityManager, NULL,
CLSCTX_INPROC_SERVER,IID_IInternetSecurityManager, (void**)&pSecurityMgr);
int policy = URLPOLICY_ALLOW;
hr = pSecurityMgr->ProcessUrlAction(L"http://www.google.com", URLACTION_SCRIPT_RUN,
(BYTE*)&policy, sizeof(policy), NULL, 0, PUAF_TRUSTED, 0);
if hr = S_FALSE, javascript execution is disabled...

Categories