Android Calling JavaScript functions in Button - javascript

I've an Android Activity and I've got a Button that button need to access some Javascript function. Simply my app get the user info(ID,pass) then go to web page(this operation doing backgrun with asynctask class) write these two info as ID and pass then user click the Log In button in my app button has to use some js function
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
this is the func. i need to use
My post and get request for connection the site are
POST//
URL url = new URL(params[0]); //http://login.cu.edu.tr/Login.aspx? site=https://derskayit.cu.edu.tr&ReturnUrl=%2f
connection=(HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(data);
writer.flush();
these codes for the put the ID and pass
GET //
reader= new BufferedReader((new InputStreamReader(connection.getInputStream())));
StringBuilder builder = new StringBuilder();
String line;
while((line= reader.readLine())!=null){
builder.append(line + "\n");
}
text=builder.toString();
there is any help or suggestion for me i am very confused about that situation and i feel really bad myself thanks for helps anyway. Have a nice day

For using Javascript without a webView to make requests!
The question has already an answer here in this question
The javax.script package is not part of the Android SDK. You can execute JavaScript in a WebView, as described here. You perhaps can use Rhino, as described here. You might also take a look at the Scripting Layer for Android project.
Also a similar question was asked here
You can execute JavaScript without a WebView. You can use AndroidJSCore. Here is a quick example how you might do it:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://your_website_here/file.js");
HttpResponse response = client.execute(request);
String js = EntityUtils.toString(response.getEntity());
JSContext context = new JSContext();
context.evaluateScript(js);
context.evaluateScript("question.vote(0);");
However, this most likely won't work outside of a WebView, because I presume you are not only relying on JavaScript, but AJAX, which is not part of pure JavaScript. It requires a browser implementation.
Is there a reason you don't use a hidden WebView and simply inject your code?
// Create a WebView and load a page that includes your JS file
webView.evaluateJavascript("question.vote(0);", null);
Otherwise:
Yes you can make HTTP POST and HTTP GET requests without using WebView. But if you want to use a webView remember Javascript in a webview is disabled by default (for security purposes). So before calling any javascript functions make sure you enable javascript in your webview like this
webView.getSettings().setJavaScriptEnabled( true );
And after that javascript will be enabled in your webView.
But in case you do not want to use a webview and javascript to make http requests. There is a lot of alternative methods you can define a Button in your activity's layout in xml. And respond with a http request on button Clicked listener!
Also remember making http Request using Android/Java default classes is a huge task and error prone and requires you to care about using async tasks to avoid blocking the UI thread.
Alternatively
In android we use ready-made library to make http requests. Google has a good library called Volley. it is easy to customize,respond to errors and it automatically making request out of the main thread.See more explanation here!. If there is still some problems comment below!

Related

How to run an EXE file through URL on .Net shared hosting

I try to run a simple ETL process on a schedule to populate a SQL Server database table on a .Net shared hosting. The EXE file will be hosted with the website and when it runs it will make some API calls and get data to update the website's SQL table.
My hosting company allows such thing (to call an exe file on schedule) with an extra fee, but they require me to have it wrapped and be called using URL. They don't mind any technology to use as long as I provide a URL. I did few attempt to get this setup working with no luck. For example I tried two ways below: Note, I just started to learn JavaScript, I use C# but this is my first time attempt to do something like that and I might be completely off. Any help will be appreciated.
<html>
<head>
<title>Open PMETL</title>
<script type="text/javascript">
function runProgram()
{
try {
var shell = new ActiveXObject("WScript.Shell");
var myPMETL="http://trudat.live/RefreshData.exe";
shell.Run(myPMETL);
}
catch (e) {
alert(e.message);
}
}
function runProgram02() {
if (window.ActiveXObject) {
try {
var excelApp = new ActiveXObject ("Excel.Application");
excelApp.Visible = true;
}
catch (e) {
alert (e.message);
}
}
else {
alert ("Your browser does not support this example.");
}
}
</script>
</head>
<body>
Run program
Run program02
</body>
</html>
I was able to achieve that by adding a new page to my ASP.NET application and port the console application into the code-behind C# and invoke the code through the Page_Load() method. This allowed my to give the hosting company a URL like http://mydomain/ExePage.aspx without impacting my original application since this new page is not reachable from the application's menu. it was a convenient way to give me what I needed.
I assume this is not a typical solution since I had the advantage to have the source code of the EXE program, but nevertheless it is a very effective, and this might help someone in the future.

Enable users of a WebRtc app to download webrtc logs via javascript

I've seen the following:
chrome://webrtc-internals
However I'm looking for a way to let users click a button from within the web app to either download or - preferably - POST WebRtc logs to an endpoint baked into the app. The idea is that I can enable non-technical users to share technical logs with me through the click of a UI button.
How can this be achieved?
Note: This should not be dependent on Chrome; Chromium will also be used as the app will be wrapped up in Electron.
You need to write a javascript equivalent that captures all RTCPeerConnection API calls. rtcstats.js does that but sends all data to a server. If you replace that behaviour with storing it in memory you should be good.
This is what I ended up using (replace knockout with underscore or whatever):
connectionReport.signalingState = connection.signalingState;
connectionReport.stats = [];
connection.getStats(function (stats) {
const reportCollection = stats.result();
ko.utils.arrayForEach(reportCollection, function (innerReport) {
const statReport = {};
statReport.id = innerReport.id;
statReport.type = innerReport.type;
const keys = innerReport.names();
ko.utils.arrayForEach(keys, function (reportKey) {
statReport[reportKey] = innerReport.stat(reportKey);
})
connectionReport.stats.push(statReport);
});
connectionStats.push(connectionReport);
});
UPDATE:
It appears that this getStats mechanism is soon-to-be-deprecated.
Reading through js source of chrome://webrtc-internals, I noticed that the web page is using a method called chrome.send() to send messages like chrome.send('enableEventLogRecordings');, to execute logging commands.
According to here:
chrome.send() is a private function only available to internal chrome
pages.
so the function is sandboxed which makes accessing to it not possible

online offline check using javascript [duplicate]

This question already has answers here:
Detect the Internet connection is offline?
(22 answers)
Closed 8 years ago.
How do you check if there is an internet connection using jQuery? That way I could have some conditionals saying "use the google cached version of JQuery during production, use either that or a local version during development, depending on the internet connection".
The best option for your specific case might be:
Right before your close </body> tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
This is probably the easiest way given that your issue is centered around jQuery.
If you wanted a more robust solution you could try:
var online = navigator.onLine;
Read more about the W3C's spec on offline web apps, however be aware that this will work best in modern web browsers, doing so with older web browsers may not work as expected, or at all.
Alternatively, an XHR request to your own server isn't that bad of a method for testing your connectivity. Considering one of the other answers state that there are too many points of failure for an XHR, if your XHR is flawed when establishing it's connection then it'll also be flawed during routine use anyhow. If your site is unreachable for any reason, then your other services running on the same servers will likely be unreachable also. That decision is up to you.
I wouldn't recommend making an XHR request to someone else's service, even google.com for that matter. Make the request to your server, or not at all.
What does it mean to be "online"?
There seems to be some confusion around what being "online" means. Consider that the internet is a bunch of networks, however sometimes you're on a VPN, without access to the internet "at-large" or the world wide web. Often companies have their own networks which have limited connectivity to other external networks, therefore you could be considered "online". Being online only entails that you are connected to a network, not the availability nor reachability of the services you are trying to connect to.
To determine if a host is reachable from your network, you could do this:
function hostReachable() {
// Handle IE and more capable browsers
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );
// Issue request and handle response
try {
xhr.send();
return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );
} catch (error) {
return false;
}
}
You can also find the Gist for that here: https://gist.github.com/jpsilvashy/5725579
Details on local implementation
Some people have commented, "I'm always being returned false". That's because you're probably testing it out on your local server. Whatever server you're making the request to, you'll need to be able to respond to the HEAD request, that of course can be changed to a GET if you want.
Ok, maybe a bit late in the game but what about checking with an online image?
I mean, the OP needs to know if he needs to grab the Google CMD or the local JQ copy, but that doesn't mean the browser can't read Javascript no matter what, right?
<script>
function doConnectFunction() {
// Grab the GOOGLE CMD
}
function doNotConnectFunction() {
// Grab the LOCAL JQ
}
var i = new Image();
i.onload = doConnectFunction;
i.onerror = doNotConnectFunction;
// CHANGE IMAGE URL TO ANY IMAGE YOU KNOW IS LIVE
i.src = 'http://gfx2.hotmail.com/mail/uxp/w4/m4/pr014/h/s7.png?d=' + escape(Date());
// escape(Date()) is necessary to override possibility of image coming from cache
</script>
Just my 2 cents
5 years later-version:
Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.
On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.
You can mimic the Ping command.
Use Ajax to request a timestamp to your own server, define a timer using setTimeout to 5 seconds, if theres no response it try again.
If there's no response in 4 attempts, you can suppose that internet is down.
So you can check using this routine in regular intervals like 1 or 3 minutes.
That seems a good and clean solution for me.
You can try by sending XHR Requests a few times, and then if you get errors it means there's a problem with the internet connection.
I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.
http://tomriley.net/blog/archives/111
i have a solution who work here to check if internet connection exist :
$.ajax({
url: "http://www.google.com",
context: document.body,
error: function(jqXHR, exception) {
alert('Offline')
},
success: function() {
alert('Online')
}
})
Sending XHR requests is bad because it could fail if that particular server is down. Instead, use googles API library to load their cached version(s) of jQuery.
You can use googles API to perform a callback after loading jQuery, and this will check if jQuery was loaded successfully. Something like the code below should work:
<script type="text/javascript">
google.load("jquery");
// Call this function when the page has been loaded
function test_connection() {
if($){
//jQuery WAS loaded.
} else {
//jQuery failed to load. Grab the local copy.
}
}
google.setOnLoadCallback(test_connection);
</script>
The google API documentation can be found here.
A much simpler solution:
<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
and later in the code:
var online;
// check whether this function works (online only)
try {
var x = google.maps.MapTypeId.TERRAIN;
online = true;
} catch (e) {
online = false;
}
console.log(online);
When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.

Selenium: How to Inject/execute a Javascript in to a Page before loading/executing any other scripts of the page?

I'm using selenium python webdriver in order to browse some pages. I want to inject a javascript code in to a pages before any other Javascript codes get loaded and executed. On the other hand, I need my JS code to be executed as the first JS code of that page. Is there a way to do that by Selenium?
I googled it for a couple of hours, but I couldn't find any proper answer!
Selenium has now supported Chrome Devtools Protocol (CDP) API, so , it is really easy to execute a script on every page load. Here is an example code for that:
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': 'alert("Hooray! I did it!")'})
And it will execute that script for EVERY page load. More information about this can be found at:
Selenium documentation: https://www.selenium.dev/documentation/en/support_packages/chrome_devtools/
Chrome Devtools Protocol documentation: https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-addScriptToEvaluateOnNewDocument
Since version 1.0.9, selenium-wire has gained the functionality to modify responses to requests. Below is an example of this functionality to inject a script into a page before it reaches a webbrowser.
import os
from seleniumwire import webdriver
from gzip import compress, decompress
from urllib.parse import urlparse
from lxml import html
from lxml.etree import ParserError
from lxml.html import builder
script_elem_to_inject = builder.SCRIPT('alert("injected")')
def inject(req, req_body, res, res_body):
# various checks to make sure we're only injecting the script on appropriate responses
# we check that the content type is HTML, that the status code is 200, and that the encoding is gzip
if res.headers.get_content_subtype() != 'html' or res.status != 200 or res.getheader('Content-Encoding') != 'gzip':
return None
try:
parsed_html = html.fromstring(decompress(res_body))
except ParserError:
return None
try:
parsed_html.head.insert(0, script_elem_to_inject)
except IndexError: # no head element
return None
return compress(html.tostring(parsed_html))
drv = webdriver.Firefox(seleniumwire_options={'custom_response_handler': inject})
drv.header_overrides = {'Accept-Encoding': 'gzip'} # ensure we only get gzip encoded responses
Another way in general to control a browser remotely and be able to inject a script before the pages content loads would be to use a library based on a separate protocol entirely, eg: Chrome DevTools Protocol. The most fully featured I know of is playwright
If you want to inject something into the html of a page before it gets parsed and executed by the browser I would suggest that you use a proxy such as Mitmproxy.
If you cannot modify the page content, you may use a proxy, or use a content script in an extension installed in your browser. Doing it within selenium you would write some code that injects the script as one of the children of an existing element, but you won't be able to have it run before the page is loaded (when your driver's get() call returns.)
String name = (String) ((JavascriptExecutor) driver).executeScript(
"(function () { ... })();" ...
The documentation leaves unspecified the moment at which the code would start executing. You would want it to before the DOM starts loading so that guarantee might only be satisfiable with the proxy or extension content script route.
If you can instrument your page with a minimal harness, you may detect the presence of a special url query parameter and load additional content, but you need to do so using an inline script. Pseudocode:
<html>
<head>
<script type="text/javascript">
(function () {
if (location && location.href && location.href.indexOf("SELENIUM_TEST") >= 0) {
var injectScript = document.createElement("script");
injectScript.setAttribute("type", "text/javascript");
//another option is to perform a synchronous XHR and inject via innerText.
injectScript.setAttribute("src", URL_OF_EXTRA_SCRIPT);
document.documentElement.appendChild(injectScript);
//optional. cleaner to remove. it has already been loaded at this point.
document.documentElement.removeChild(injectScript);
}
})();
</script>
...
so I know it's been a few years, but I've found a way to do this without modifying the webpage's content and without using a proxy! I'm using the nodejs version, but presumably the API is consistent for other languages as well. What you want to do is as follows
const {Builder, By, Key, until, Capabilities} = require('selenium-webdriver');
const capabilities = new Capabilities();
capabilities.setPageLoadStrategy('eager'); // Options are 'eager', 'none', 'normal'
let driver = await new Builder().forBrowser('firefox').setFirefoxOptions(capabilities).build();
await driver.get('http://example.com');
driver.executeScript(\`
console.log('hello'
\`)
That 'eager' option works for me. You may need to use the 'none' option.
Documentation: https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/capabilities_exports_PageLoadStrategy.html
EDIT: Note that the 'eager' option has not been implemented in Chrome yet...

Call javascript function from windows service c#

I need to call a javascript function inside a chrome-window from a windows service written in c#.
The browser is entirely at my disposal so I can configuration is no problem.
For example, the windows service is a file checker, when a certain file is changed there has to popup a js alert.
-EDIT-
The following works fine for client to client communication (server-side code).
So when a specific event happens on the server I can display this on the client (I hoped commented would do that)
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;
using SignalR.Hosting.Self;
using SignalR.Hubs;
namespace Net.SignalR.SelfHost
{
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8081/";
var server = new Server(url);
server.MapHubs();
server.Start();
Console.WriteLine("SignalR server started at " + url);
Console.ReadLine();
// Clients[collection].flush("bericht: " + message + collection);
}
//public void PushMessage(string bericht)
//{
// var hubConnection = new HubConnection("http://localhost:8081/");
// var serverHub = hubConnection.CreateProxy("CollectionHub");
// serverHub.On("flush", message => System.Console.WriteLine(message));
// hubConnection.Start().Wait();
// serverHub.Invoke("Subscribe", "Product");
// string line = null;
// while ((line = bericht) != null)
// {
// serverHub.Invoke("Publish", line, "Product").Wait();
// }
// System.Console.Read();
//}
public class CollectionHub : Hub
{
public void Subscribe(string collectionName)
{
Groups.Add(Context.ConnectionId, collectionName);
Console.WriteLine("Subscribed to: " + collectionName);
//serverHub.Invoke("Publish", "dit is een eerste test", "Product").Wait();
}
public Task Unsubscribe(string collectionName)
{
return Clients[collectionName].leave(Context.ConnectionId);
}
public void Publish(string message, string collection)
{
Clients[collection].flush("bericht: " + message + collection);
}
}
}
}
Sounds like you are describing SignalR.
What is ASP.NET SignalR?
ASP.NET SignalR is a new library for ASP.NET
developers that makes it incredibly simple to add real-time web
functionality to your applications. What is "real-time web"
functionality? It's the ability to have your server-side code push
content to the connected clients as it happens, in real-time.
You may have heard of WebSockets, a new HTML5 API that enables
bi-directional communication between the browser and server. SignalR
will use WebSockets under the covers when it's available, and
gracefully fallback to other techniques and technologies when it
isn't, while your application code stays the same.
SignalR also provides a very simple, high-level API for doing server
to client RPC (call JavaScript functions in your clients' browsers
from server-side .NET code) in your ASP.NET application, as well as
adding useful hooks for connection management, e.g. connect/disconnect
events, grouping connections, authorization.
What can you do with ASP.NET SignalR?
SignalR can be used to add any
sort of "real-time" web functionality to your ASP.NET application.
While chat is often used as an example, you can do a whole lot more.
Any time a user refreshes a web page to see new data, or the page
implements Ajax long polling to retrieve new data, is candidate for
using SignalR.
What it basicly does, is giving you access to the client AND server side functions in both directions, a simple example of it's usage can be found on the asp.net website which will give you a good idea on how to use it and what it's capable of doing.
You want to be using something like signal IR to do that, its what its designed for, essentially you are describing real time functionality;
Signal IR can be found here and has a great section on javascript in its wiki
In particular you probably want to take a look at Hubs

Categories

Resources