Click a button in CefSharp browser in Windows Forms - javascript

I'm trying to click a button on a webpage (kahoot.it), and I already know that I probably need to use Javascript for that which is fine, as long as it stays with 1 line of JavaScript because that's easy to implement in WinForms. I don't have much information on the button,
only:
<button type="submit" value="Submit" class="enter-button__EnterButton-sc-1o9b9va-0 kxpxeu" data-functional-selector="join-game-pin"><span>Enter</span></button>
Could you guys please help? There's only one button on the page, maybe that helps.

You need to write a piece of javascript code and run it when the page loaded.
Run script after page loaded
To run the code after the page loaded, you can use ExecuteScriptAsyncWhenPageLoaded method or you can handle FrameLoadEnd or LoadingStateChanged.
DOM manipulation - find element, set value, click on button
For the javascript code, you can use any of the available javascript functions. for example find the element using getElemenetsByName, getElementsByTagName or getElementById.
After you found the element, you can set its value or for example for a button you can click on it by calling its click() method.
CefSharp Example - Browse a URL, fill an input and click on a button
The following code, adds a ChromiumWebBrowser control to a Form. Then it browses google and fill the search box with a text and clicks on the search button:
//using CefSharp;
//using CefSharp.WinForms;
ChromiumWebBrowser browser;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
browser = new ChromiumWebBrowser("https://www.google.com/");
browser.Dock = DockStyle.Fill;
Controls.Add(browser);
var script = #"
document.getElementsByName('q')[0].value = 'CefSharp C# Example';
document.getElementsByName('btnK')[0].click();
";
browser.ExecuteScriptAsyncWhenPageLoaded(script);
}
Example 2
In the following example, using ExecuteScriptAsync you can fill the search box with a text and clicks on the search button programmatically:
//using CefSharp;
//using CefSharp.WinForms;
ChromiumWebBrowser browser;
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
browser = new ChromiumWebBrowser("https://www.google.com/");
browser.Dock = DockStyle.Fill;
Controls.Add(browser);
}
private void button1_Click(object sender, EventArgs e)
{
var script = #"
document.getElementsByName('q')[0].value = 'CefSharp C# Example';
document.getElementsByName('btnK')[0].click();
";
browser.ExecuteScriptAsync(script);
}
Note: In your case, for kahoot.it, the script should be:
var script = #"
document.getElementById('game-input').value = '123';
document.getElementsByTagName('button')[0].click();
";

Changing Target Framework version to 4.7.2 from 4.0 fixed for me
True Target Framework Version

Related

Android Studio WebView click on a loaded html page's element

I am loading a website in my app that contains an element I want to programmatically click (automate the click) as when this is clicked is time sensitive. I have the timing part down but need to trigger this element via an on screen click. I have read that performClick() "should" work but I have no way to verify if its actually clicking in the webview or not. The element in the html I need to trigger with a "touch" is called 'overlay'. Could someone provide me with a template that could do this?
You can use the below snippet to trigger at touch.
Video_Player.my_runnable = new Runnable()
{
#Override
public void run()
{
view.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis() + 50,MotionEvent.ACTION_DOWN,300,300,0));
view.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis() + 50,MotionEvent.ACTION_UP,300,300,0));
}
};

UrbanAirship - HTML Button - set tag to pass to code

What I am wanting to do is simple. I am using UrbanAirship to show a modal view ("In-app Automation"), which is HTML. I have a button in my HTML. The message/view is showing fine when the event is fired. Right now I have in the HTML for the button:
<button class="light" type="button" onclick="UAirship.close()">OK</button>
When the button is tapped, the call to UAirship.close() works fine and closes the message. I setup a listener in my Android code, such as follows:
UAirship.shared()
.getInAppMessagingManager()
.addListener(new InAppMessageListener() {
#Override
public void onMessageDisplayed(#NonNull String scheduleId, #NonNull InAppMessage message) {
// gets here fine
}
#Override
public void onMessageFinished(#NonNull String scheduleId, #NonNull InAppMessage message, #NonNull ResolutionInfo resolutionInfo) {
// gets here fine as well
}
});
It gets into those methods without any issues when the message/view shows and dismisses. However, I want to be able to detect one particular button was tapped vs. others I have in the HTML. Is there a way to go about this easily, so that some custom tag or something can be passed in the "ResolutionInfo" object or "InAppMessage"?
My hopes were that there would be something like "UAirship.close('tag')", where that tag would be passed back. Or even a custom HTML tag I can put on the button that would be recognized in the code. Really just any way of going about it is fine, I just can't seem to find in the documentation how to properly do this with HTML.
I'm looking at the documentation here. I see the UAirship.runAction() method, but it's not really clear to me what a simple implementation would be for this (also, the "CustomAction" class referenced in the action registering doesn't even exist in the library it seems..).
I basically just need to call one line of code in my Activity when the Airship message closes after that button is tapped.
Thoughts?
I've found that this solution works, although there may be a better one out there.
In the HTML, for the button, call the close() and then a runAction() call:
onclick="UAirship.close(); UAirship.runAction('my_action', null, null)"
Then in the code, in my onCreate() in my Activity, I have this:
final String actionName = "my_action";
Action customAction = new Action() {
#NonNull
#Override
public ActionResult perform(#NonNull ActionArguments actionArguments) {
String buttonActionName = actionArguments.getMetadata().getString(ActionArguments.REGISTRY_ACTION_NAME_METADATA);
if (buttonActionName.equals(actionName)) {
// DO WHAT IS NEEDED HERE
}
return ActionResult.newEmptyResult();
}
};
​
UAirship.shared()
.getActionRegistry()
.registerAction(customAction, actionName);

Slight flickering due to jQuery's $(document).ready when manipulating DOM in DocumentCompleted event of WebBrowser

I'm using WebBrowser c# to scrape a website and manipulate it before displaying to user.
Example, I want all the Buttons of the current website to be hidden.
I do so by injecting Javascript, but I believe it's too late as the page is already rendered out, thus, a slight flicker (the flicker website has all the button shown) before all buttons are hidden.
(All buttons shown -> JavaScript .ready(function(){}) inject executed -> All buttons hidden).
private void browser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string js = "$(document).ready(function() { hideButtons(); })";
script = browser1.Document.createElement("script");
script.SetAttribute("text", js);
head.AppendChild(script);
}
Code above : JavaScript inject.
How to solve the flicker (when all the buttons are shown for a quick moment before hiding them all back after jQuery execution)?
I have tried manipulating the DOM object in DocumentCompleted method by setting its OuterHtml to nothing "" or by setting css attribute to display:none; but there is still such slight flicker.
private void browser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var b = browser1.Document.getElementById("btn1");
b.OuterHtml = "";
}
Is there a way to manipulate DOM objects before rendering out to the users?
What event do I call?
The only thing I can think of that would work is to intercept the navigating function, pull the page manually and then render the HTML in the browser window.
private void browser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
//Cancel the request
e.Cancel = true;
using (WebClient client = new WebClient())
{
string html = client.DownloadString(e.Url.ToString());
//Find the text that you want to replace here and replace it
browser1.DocumentText = html;
}
}

LinkButton click doesn't trigger with no javascript

Web forms user control generating a LinkButton in PageInit:
LinkButton b1 = new LinkButton();
b1.Click += new EventHandler(Button_Click);
public void Button_Click(object sender, EventArgs e) {
//redirects to another page .. (no js defined here or in the ascx surrounding this button)
}
Why doesn't this wok when my javascript is disabled, if I used no js at all when creating the button?
How do I prevent this?
Yes this is webforms (sorry, unable to comment below).
The issue is that's how web forms manages its events with the server - as I understand it anyway (correct me if I'm wrong). Use html 5 instead. You can make the page postback to the server at the same url with a query string and then on the server grab the query string. Not the best solution but it works; it will look something similar to this:
In your page:
<form id="aForm">
<button id="abutton" type"submit" formaction="thisPage.aspx?redirect=true">click me</button>
</form>
In your page load event on the server:
if (IsPostBack) {
object something = Request.QueryString["redirect"];
if (something == null)
//not redirecting
}

Unable to use <% ... %> in a client side button click event

I am trying to redirect to a different page based upon a value in the querystring. This is an asp.net web form page. When the cancel button is clicked the following js should execute. The button is an devexpress button.
function OnCancelClick(s, e) {
if (confirm('If you leave this page, you have to reselect the benefits. Are you sure to leave this page?')) {
var callingPage = document.getElementById("<%= CallingPage.ClientID %>").value;
alert("Calling Page: " + callingPage);
if (callingPage == "AddEmployee.aspx") {
window.location.href = ResolveUrl('~/Member/Maintenance/AddEmployee.aspx?from=VerifyPage');
} else if (callingPage == "AddDependentMember.aspx") {
}
}
CallingPage is the ID of an asp hidden field. I am setting its value during the page load. Even before this page is loaded I am getting The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)
error. Not sure whether it is due to devexpress button control or something else.
Assign the CallingPage.ClientID to a server side page variable with public accessibility:
public partial class <class / page name> : System.Web.UI.Page
{
public string callingPage = "";
protected void Page_Load(object sender, EventArgs e)
{
this.callingPage = CallingPage.ClientID;
...
}
}
then in your javascript:
var callingPage = document.getElementById("<%= this.callingPage %>").value;
Actually this is an unique issue related to devexpress controls. It looks like that we can't use <% %> within the js clientside click event of a devexpress button click event. Instead I used devexpress's hidden control, then it worked fine.
Thanks

Categories

Resources