c# How to click this submit button? - javascript

I'm trying to make a program that makes Visual studio webclients login to kahoot.it, i now am able to enter the required information to login but have no way to click the submit button...
Here is the code of the button:
<button type="submit" class="btn btn-greyscale join ng-binding" blocking="" data-functional-selector="join-button-game-pin">Enter</button>
Kind regards,
Joep van Diessen
private void button1_Click(object sender, EventArgs e)
{
HtmlDocument doc = webBrowser1.Document;
doc.GetElementById("inputSession").SetAttribute("Value", gpin);
}
private void button2_Click(object sender, EventArgs e)
{
HtmlElement headElement = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptElement = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptElement.DomElement;
element.text = #"function sayHello() $('button[type=""submit""]').first().submit()";
headElement.AppendChild(scriptElement);
webBrowser1.Document.InvokeScript("sayHello");
}

Assuming jquery
$('button[type="submit"]').first().submit()
Edit #1
element.text = #"function sayHello() { document.getElementsByTagName('form')[0].submit(); }";

Related

Troubles to open ajaxToolkit:ModalPopupExtender with JavaScript

I'm trying to open a ajaxToolkit:ModalPopupExtender with JavaScript but when I run my code and I call the function from the code behind this crash and show this error.
JavaScript runtime error: Unable to get property 'show' of undefined
or null reference
this is my JavaScript:
<script>
function closeChangeArea() {
$find('ModalChangeArea').hide();
}
function showChangeArea() {
$find('ModalChangeArea').show();
}
</script>
and this is my code:
protected void Btn_Click_Ch_Area(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gr = (GridViewRow)lb.NamingContainer;
Label ToolChange = (Label)gr.FindControl("Lbl_toolg");
Txt_Tool_Reasign.Text = ToolChange.Text;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showChangeArea();", true);
}
this is my ModalPoupExtender
<ajaxToolkit:ModalPopupExtender
ID="ModalChangeArea"
runat="server"
TargetControlID="hid"
PopupControlID="ChangeArea"
RepositionMode="RepositionOnWindowResizeAndScroll"
DropShadow="true"
PopupDragHandleControlID="moveArea">
</ajaxToolkit:ModalPopupExtender>
In asp.net control id is dynamically appended with container, in that case you will not get the control using $find to get control use clientid of asp.net control or set ClientIdMode = "Static".
Try below code to access element.
$find('<%= ModalChangeArea.ClientID %>').show();
$find('<%= ModalChangeArea.ClientID %>').hide();

Is it possible to get data from HTML forms into android while using webView?

I'm making a very simple form in HTML which is viewed in android using the webview which takes in your name using a textbox and when you click on the button, it displays it into a paragraph and it's made using both html and javascript.
This is my html code:
<!DOCTYPE html>
<html>
<body>
<p> Write your name and win your favorite game console name and win it! The winners will be announced in 4 days.</p>
Type your name here: <input id="thebox" type="text" name="value" value=""><br>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("thebox").value;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
NEW EDITED FORM
<form name="albert" action="" method="POST">
<label for="firstname"> First Name </label>
<br /><br />
<input type="text" name="firstname" id="firstname" />
<input type="submit" name="sbumit" value="Submit" />
</form>
I want to get the value from the input box called "thebox" in a variable in android on the button click and I tried lots of stuff before and I followed a method where you inject a JS file but since I know nothing about JS so I did fail trying that and here is the file that I put in my project and the file is called inject.js:
document.getElementsByTagName('form')[0].onsubmit = function () {
var objPWD, objAccount, objSave;
var str = '';
var inputs = document.getElementsByTagName('thebox');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.toLowerCase() === 'thebox') {
objAccount = inputs[i];
}
}
if(objAccount != null) {
str += objAccount.value;
}
if(objPWD != null) {
str += ' , ' + objPWD.value;
}
if(objSave != null) {
str += ' , ' + objSave.value;
}
window.AndroidInterface.processHTML(str);
return true;
};
And later as I followed that article it said that I need to put some stuff in my MainActivity but since I'm using webview for the first time, I couldn't understand much and heres the code I put into my MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
this.setContentView(webView);
// enable javascript
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JavaScriptInterface(), "AndroidInterface");
// catch events
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
try {
view.loadUrl("javascript:" + buildInjection());
} catch (IOException e) {
e.printStackTrace();
}
}
});
webView.loadUrl("http://someurl.com");
}
A nested class that I made in my MainActivity:
class JavaScriptInterface {
#JavascriptInterface
public void processHTML(String formData) {
Log.d("AWESOME_TAG", "form data: " + formData);
}
}
And finally the method that injects the code:
private String buildInjection() throws IOException {
StringBuilder buf = new StringBuilder();
InputStream inject = getAssets().open("inject.js");// file from assets
BufferedReader in = new BufferedReader(new InputStreamReader(inject, "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
buf.append(str);
}
in.close();
return buf.toString();
}
I want to get value from the html form(the-input-box) that I show in a webview in Android and is it really possible to do that and if yes how and please explain? Thanks and also please tell in what variable will I get the value.
Webview browser=(WebView)view.findViewById(R.id.webChart);
browser.getSettings().setJavaScriptEnabled(true);
browser.addJavascriptInterface(new WebAppInterface(getActivity()), "Android");
browser.loadUrl("file:///android_asset/yourHtmlFileName.html");
add this interface class, WebAppInterface
public class WebAppInterface {
Context mContext;
String data;
WebAppInterface(Context ctx){
this.mContext=ctx;
}
#JavascriptInterface
public void sendData(String data) {
//Get the string value to process
this.data=data;
}
}
your HTML code data
function loadChartData() {
var x = document.getElementById("thebox").value;
Android.sendData(x);
}
call this function when the html button click in android webview
UPDATE
1) By default javascript is disabled in webview . to enable it, get the settings of the webview and call the setJavaScriptEnabled(true); to true.
2) to create the interface between your Javascript code and your android code, you need to create Javacript interface class.
3) bind the interface between your javascript code to android code, you need to pass the reference of the interface class and an interface name that your javaScript can call to access the class.
4) pass the html file path to load into the webview(browser).
5) create the interface class like below(WebAppInterface).
see this link for more details
https://developer.android.com/guide/webapps/webview.html
6) in HTML file, create the button and add the click listener to that button and call the sendData("your value") function with interface name(Here Android).
Thats all. you can pass the value from html to your android code.
Yes you can, you can use javascript to get webpage content. Then use the webview jsInterface to return the content to you java code.
Refer this github project. and this answer and this article.
final Context myApp = this;
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(String html)
{
// process the html as needed by the app
}
}
final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");
Hope this helps.
For forms with method "GET" you can achieve this pretty simple just by overriding shouldOverrideUrlLoading method. Following solution works only if url was loaded through webview.loadUrl() method.
private class MWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// submit will end-up with url like "data:,?firstname=SomeInput&sbumit=Submit"
if (URLUtil.isDataUrl(url)) {
url = url.replace(":,?", ":/?"); //to be able to properly parse Uri
Uri uri = Uri.parse(url);
//here you can get params by field name
String firstname = uri.getQueryParameter("firstname");
//we handle this URL ourselves
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
}
To communicate a webView with native android,
this is a simple way :
in your js onClick on the button you should call url that contains your text, something like myPrefix://myData
and in android
webView.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url)
{
if(url.startsWith("myPrefix://"))
{
//get your data by split url
return true;
}
return false;
});
#Shariq
As many have already answered this question in a good way, but i think moreover you need clarification about how exactly data is flowing into the codes from webview to andorid so I won't waste bytes in writing that all redundant codes:
(I'm taking reference of your codes for better understanding )
Follow these steps in these codes to make better understanding:
Step 1:
We need to define some method on Android side that can accept some data from webview
#JavascriptInterface
//this 'formData' variable is going to accept the data from webview
public void processHTML(String formData) {
Log.d("AWESOME_TAG", "form data: " + formData);
}
Now the it's value will be available to java android side context.
Step 2:
here is your HTML side codes (webview).
if the URL you are accessing in webview is yours then you can easily write these codes to html page but if you are accessing some third party URL still you can inject this js code into webview simply by following line of code:
...
//partial code
webView.load("javascript:function myFunction() { var x = document.getElementById('thebox').value; Android.processHTML(x); } myFunction();";
...
So what's exactly happening here:
'x' is the variable in js holding the required value and then we are sending this 'x' variable to android context via method call Android.processHTML(x)
I hope it might help you in a better way
Yes, it is possible. Please try using the below code
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view_layout);
WebView webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
try {
progressDialog = new ProgressDialog(ActivityName);
progressDialog.setMessage("Loading.."); progressDialog.setCancelable(false);
webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl(YOUR_URL);
} catch (Exception e) {
e.toString();
}
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
progressDialog.dismissProgress();
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
progressDialog.dismissProgress();
}
}
You can get data from WebView by catching alert messages.
Use WebChromeClient.
mWebview = (WebView)findViewById(R.id.yourwebviewlayout);
final class YourWebChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Toast.makeText(getApplicationContext(),
"alert message = " + message,
Toast.LENGTH_SHORT).show();
result.confirm();
return true;
}
}
mWebview.setWebChromeClient(new YourWebChromeClient());
Best js to inject have used so far, it collects data from all forms on submit
document.getElementsByTagName("form")[0].addEventListener("submit", myFunction);
function myFunction()
{
var data="";
var inputs = document.forms[0].getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
var field = inputs[i];
if (field.type != 'submit' && field.type != 'reset' && field.type != 'button')
data += '' + field.name + '=' + field.value+'\n';
}
window.AndroidInterface.processHTML(data);
return true;
}

change date label by user

I'm using C#.net to program a reservation system
I want to let the user change date through the arrows as shown on the picture (please click on the link)
date image
I have done from displaying the current date on the screen but I just don't know how to let the user use the arrows to change the dates
these are the html codes:
<asp:Label ID="lblServerDateTime" runat="server" CssClass="auto-style13" style="font-size:30px;" />
and these are the C# code
protected void page_load(object sender, EventArgs e)
{
lblServerDateTime.Text = DateTime.Now.ToString("M");
}
This snippets may help you:
Aspx
<asp:Button Text="Down" ID="btnDown" runat="server" OnClick="btnDown_Click" />
<asp:Label ID="lblServerDateTime" runat="server" CssClass="auto-style13" Style="font-size: 30px;" />
<asp:Button Text="UP" ID="btnUp" runat="server" OnClick="btnUp_Click" />
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblServerDateTime.Text = DateTime.Now.ToString("dd MMMM");
calCurrentDay.SelectedDate = DateTime.Now;
// Sets current date on initially.
}
}
protected void btnUp_Click(object sender, EventArgs e)
{
//Up button click will increase the date by one day
DateTime.TryParse(lblServerDateTime.Text, out d);
d = d.AddDays(1);
lblServerDateTime.Text = d.ToString("dd MMMM");
calCurrentDay.SelectedDate = d;
}
protected void btnDown_Click(object sender, EventArgs e)
{
//Up button click will decrease the date by one day
DateTime d;
DateTime.TryParse(lblServerDateTime.Text, out d);
d = d.AddDays(-1);
lblServerDateTime.Text = d.ToString("dd MMMM");
calCurrentDay.SelectedDate = d;
}

How to call javascript from code behind for Repeater control

There is a span element that need to load data dynamically from a Repeater control.
The problem that I encounter is only first span element can display the value. The subsequent will display blank.
I've simplify the code behind as below.
private int incre = 0;
protected void Page_Load(object sender, EventArgs e)
{
foreach (RepeaterItem ritem in FeaturedRepeater.Items)
{
HtmlGenericControl span = ritem.FindControl("countdown") as HtmlGenericControl;
span.Load += new EventHandler(test);
}
}
protected void test(object sender, EventArgs e)
{
HtmlGenericControl span = (HtmlGenericControl)sender;
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "timer(" + incre + ")", true);
incre++;
}
Javascript function in .aspx file example as below:
function timer(increment, timespan) {
var id = 'ContentPlaceHolder1_FeaturedRepeater_countdown_' + increment;
document.getElementById(id).innerHTML = id;
}
HTML part:
<asp:Repeater runat="server" ID="FeaturedRepeater" OnItemDataBound="FeaturedRepeater_ItemDataBound">
<ItemTemplate>
<span id='countdown' runat="server"></span>
</ItemTemplate>
</asp:Repeater>
Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("CallMyFunction{0}", incre), "timer(" + incre + ");", true);
you can't register the same key more then one time.
that's why changing "CallMyFunction" to string.Format("CallMyFunction{0}", incre) will work
btw
and ; after every javascript function call.

ASP.NET: HtmlGenericControl <DIV> - refresh

I have a DIV element:
<div runat="server" id="path">Nothing here... yet</div>
and JavaScript which changes its content dynamically. After some actions my element looks like this (tested with Firebug, JS is ok):
<div runat="server" id="path">FirstTest - SecondTest - ThirdTest</div>
Then I'd like to save it to text file (<asp:Button runat="server"...):
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
Button1.Click += new EventHandler(this.GreetingBtn_Click);
}
void GreetingBtn_Click(Object sender, EventArgs e)
{
HtmlGenericControl path = (HtmlGenericControl)Page.FindControl("path");
Response.AddHeader("content-disposition", "attachment;filename=download.txt");
Response.ContentType = "text/plain";
Response.Write(path.InnerText);
Response.Flush();
Response.Clear();
Response.End();
}
</script>
It also works OK (SaveDialog popups, user choose location), but... in output file there's only one line "Nothing here... yet". It looks like he doesn't react to changes made by JavaScript!
How can I force him to refresh DIV, so I can always save up-to-date content?
Thanks for any help!
You could update an asp:Hidden with the new value and use that value instead on the post back. The PlaceHolder control is not designed to be a two-way control.
E.g.
function UpdateText()
{
var text = ...;
document.getElementById("<%= path.ClientID %>").innerText = text;
document.getElementById("<%= pathHidden.ClientID %>").value = text;
}

Categories