Get notified about manually clicked links in Selenium WebDriver using C# - javascript

I'm using the ChromeWebDriver together with Selenium. The application is partically controlled automatically. Now I want the user to navigate to a page, where he has to choose a link from some list like
<ul>
<li>Google</li>
<li>Ecosia</li>
<li>Yahoo</li>
</ul>
I want to get the link automatically, where the user clicked on. As example, when he clicks on Google, I need some kind of event, that gave me http://google.de in C#. There exist a WebDriverEventListener, his ElementClicked event is exactly what I need:
private void EventDriver_ElementClicked(object sender, WebElementEventArgs e) {
if(e.Element.TagName == "a") {
string link = e.Element.GetAttribute("href");
MessageBox.Show($"User has clicked on link {link}");
}
}
But the big problem here: ElementClicked is only fired on clicks triggered by Selenium using C#. All events have this issue. For example, Navigated got fired after calling driver.Navigate().GoToUrl("http://stackoverflow.com"), but not after manually clicking on a link in the browser.
To solve this, I think its necessary to forward client-side JS events. Like this pseudocode:
$('a').click(function() {
SeleniumBackend.NotifyAboutClickEvent('a', $(this));
});
I know there is a method called ExecuteScript which allows to run JS in the browser. It seems possible to catch a direct return like
string jsReturnValue = driver.ExecuteScript("return 'test';");
For this case, that's not enough, since some sort of callback would be needed to be async.
object clickedLink = sharedWebDriver.ExecuteAsyncScript(#"
var callback = arguments[arguments.length - 1];
clickedLink('http://google.de');
");
That works, issue here: Only once. I can't bind an eventhandler, which notify me about later clicks...

It looks like you are creating the initial menu page. If that's true, you can just set a JS global variable using an onlick event and then use JavascriptExecutor to grab the variable setting and then use that to determine what link they clicked.
...or better yet, you can just detect the browser URL after they click and know where they went.

Related

How to automatically push button after mouse is (automatically) hovering on it

I am building a bigger application in React, JavaScript and HTMLusing Visual Studio Code.
I am using a third party router to log-in inside a small robot I built. This robot will turn on using a relay which is triggered by a combobox and a related button which will apply the combobox choice. Also I am new to JavaScript and HTML and for this reason I learned how to deploy a website and I prepared a minimal verifiable example which can be found here https://comboboxtest.netlify.com/ and here you can also get the source code if needed.
The goal of the application after I launch Visual Studio will be:
1) log-in inside the router,
2) automatically trigger the combobox and
3) automatically apply the combobox choice using the Apply button.
For better showing this see print screen below:
The problem: In order to access to the router there is an external interface that I didn't write because is from the router. I navigated through the interface and arrived to the Apply button as shown below in the HTML code:
So the operations are the following:
1) I trigger the relays using the combobox
2) using the mouse I have to hover on the Apply button
3) After the mouse is on the button (button hovered) I can click and apply the choice
4) The choice should be confirmed by the statement to become green.
What is not working: I can trigger the combobox, but I am not able to atomatically hover and click on the apply button.
Below the most important part of the code I am using:
property string get_relay_comboBox: "
var comboBox = document.getElementsByName('859-2-2')[0];
// find a target element.
if (comboBox) {
// Add event listener for combobox
comboBox.addEventListener('change', function (e) {
console.log('Change event detected:', e);
});
// Get new option index by flipping the current selected index
var newIdx = (comboBox.selectedIndex + 1) % 2;
// set the new index
comboBox.selectedIndex = newIdx;
// fire change event
comboBox.dispatchEvent(new Event('change'));
}
else {
console.error('comboBox not found!');
}
";
property string applyBtn: "
function fun('btnb btnhov') {
document.getElementById('btn_Apply').click();
}
";
What I tried so far
1) I research for a while the problem and I found this and also the following post which helped to understand how to trigger the combobox.
2) I right clicked on the router interface right on the Apply button and opened the Inspect Element menu and went to the Show DOM properties I found that maybe the following sreen-shot could be useful:
3) This I used to understand the HTML part and in fact I understood that it is important the way components should be called but still could't figure out how to accept the choice of the combobox using the button.
4) Following this source which is the basic way to call a clicked event I simply applied it as it is possible to show it below:
function fun('btnb btnhov') {
document.getElementById('btn_Apply').click();
}
But I didn't work and I think that at this point the most important problem as explained would be how to detect a mousover event and after that, push the button.
How to do that?
EDITS
I also tried to rewrite the function in the following way:
property string applyBtn: "
var btnApply = document.getElementById('btn_Apply');
if(btnApply) {
// Try add event listener for button
btnApply.addEventListener('change', function(e) {
console.log('Change event detected:', e);
});
// Push button
// Here the button should be pushed (or hovered first????)
}
else {
console.error('btnApply not found!');
}
";
Thanks to anyone who could please guide to the right direction to solving this problem.

Call JavaScript function after Telerik RadPageView finishes loading?

I'm using Telerik UI for asp.net. Specifically I'm using RadTabStrip with partial page postbacks to allow the user to tab through different sets of data. When the user clicks a tab, some code executes and loads data just for that tab.
I've figured out how to execute codebehind: I set the OnTabClick property of the RadTabStrip, and then in codebehind I check what tab was clicked.
E.g.
protected void tab_Click(object sender, RadTabStripEventArgs e)
{
if (e.Tab.Text == "Info")
{
populateInfoTab();
}
}
private void populateInfotab()
{
// Do some stuff
}
However, I can't figure out how to execute client side javascript after a specific tab is clicked. What I tried:
Set OnClientTabSelected property, and then add some javascript:
function tab_ClientClick(sender, args)
{
var tab = args.get_tab();
if(tab.get_text() == "Info")
{
alert("Tab Clicked");
}
}
The problem is that I need to set the InnerHtml of some div in the clicked pageview after it is clicked. The div does not exist on page load (that specific RadPageView is hidden) so I cannot set it then. Once the user clicks into the tab, and after the page view loads, I need to be able to update the div's InnerHtml through JavaScript.
How would I go about doing this?
First option - if you do not set the RenderSelectedPageOnly property to true, all page views will be rendered on the initial load and you will be able to use JS to find/modify elements in them.
Second option - just set the content from the server as soon as you load the UC, this will usually make things simpler.
Third option - use client-side events (offered by the native PageRequestManager class or the RadAjaxManager, depending on how you setup your AJAX interactions) to execute when the response is received. The difficulty here is to determine which is the postback you need. Looking for the desired element and only executing logic if it exists is the simplest flag you can opt for.
Fourth option - register a script from the server code that will call your function, something like:
populateInfoTab();
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "someKey", "myDesiredFunction()", true);
where you may want to use the Sys.Application.Load to ensure it is executed later than IScriptControl initialization.

Android - Webview Javascript to call a function for a specific DIV class

I am loading a JS webpage in my WebView. The webpage looks like a calendar and has items on the calendar that, when clicked or double-clicked, call functions defined on the page.
When a user taps once on the item, I want it to call the proper function as well as do the same for tapping twice on it. I know this is android, but users are expecting the function to happen when "double-clicking".
The function for double-clicking the item is:
function openPairingDetails(tripSequenceNumber) {
var url = "/csswa/ea/fa/getPairingDetails.do?popup=true&tripSequenceNumber=" + tripSequenceNumber;
var features = "height=600,width=900,location=no,menubar=no,resizable=no,scrollbars=yes,status=no,toolbar=no";
openWindow(url, features);
return false;
For now at least, all the items that the user will be double-clicking are of the same class:
<div class="boardpiece clickable" onclick="selectPairing(event, this);" ondblclick="openPairingDetails('5545220');"
So, the short version is this: I need to display the webpage (done) and allow the user to single-click to select the item and double-click to open the item. Each of these events link to a defined function. So, do I set up an OnClickListener to initiate a JS function on a single/double click of the DIV CLASS?
edit: I do not have the luxury of altering the website.
edit 2: Here is my logic: Page is displayed with an object. That object has a specific div class. The object ID is dynamic so it cannot be used. The object calls a specific function when either single or double clicked. Can I set a tap listener to call those specific functions? In other words - if the user taps once on one of these objects, the "onClick" function is called. If the user performs a longpress on an object, the "onDblClick" function is called. Can I set these to call the respective functions?
public void onClick(View v)
{
// some other code here
}
public boolean onLongClick(View view)
{
// just showing a Toast here
return false;
}
Thank you
~ Dan
double click cannot handle it in android webview. Any click listener on webview will work complete webview not on any element.
better u need to implement it on div only with this link
link
den use javascript bridge interface if u want to some android native related stuff

Warning when clicking external links and how to add it to a link class

I'm not sure how to do a pop-up that warns when you are clicking on external links, using javascript.
I figured that it would be handy to put a class on my external links as well, but I'm not quite sure it's done correct as it is now either. This is the HTML I'm using at the moment:
<div id="commercial-container">
<img src="picture1.jpg" />
<img src="pciture2.jpg" />
<img src="picture3.jpg" />
<img src="picture4" />
</div>
I'm very new to javascript and very unsure on how to solve my problems. The pretty much only thing I figured out so far is that I will have to use window.onbeforeload but I have no clue on how to figure out how to write the function I need.
I want to keep my javascript in a separated .js document instead of in the HTML as well.
Call the confirm() function from the onClick attribute. This function returns true if the user clicks OK, which will open the link, otherwise it will return false.
<img src="picture1.jpg"/>
Hope this helps.
You can do it by adding a click event handler to each link. This saves having to use a classname.
window.onunload will run even if the user is just trying to close your site, which you may not want.
staying in site
going external
<script>
var a = document.getElementsByTagName('a');
var b = a.length;
while(b--){
a[b].onclick = function(){
if(this.href.indexOf('yourwebsitedomain.com')<0){
//They have clicked an external domain
alert('going external');
}
else{
alert('staying in your site');
}
};
}
</script>
Since you're new to Javascript I advice you to use a javascript framework to do all the "heavy work" for you.
For example with JQuery you can easily bind an onClick event to all external links by doing:
$(".external").click(function(event) {
var confirmation = confirmation("Are you sure you want to leave ?");
if (!confirmation) {
// prevents the default event for the click
// which means that in this case it won't follow the link
event.preventDefault();
}
});
This way every time a user clicks on a link with the external class, a popup message box asking for a confirmation to leave will be prompt to the user and it will only follow the link if the user says "yes".
In case you want only to notify without taking any actions you can replace the confirmation by a simple alert call:
$(".external").click(function(event) {
alert("You are leaving the site");
});
If the user click an image,div,.. you need to look for the parent node. !There could be several elements wrapped with a-tag.
document.addEventListener('click',function(event){
var eT=(event.target||event.srcElement);
if((eT.tagName.toLowerCase()==='a' && eT.href.indexOf('<mydomain>')<0)
|| (eT.parentNode!==null && eT.parentNode.tagName.toLowerCase()==='a'
&& eT.parentNode.href.indexOf('<mydomay>')<0))
{
//do someting
}
else if(eT...){
...
}
},false);
Two side notes:
If you want to keep track a user by cookie or something similar, it's good practice to check external links, set a timeout and make a synchronic get request to renew.
It's better to add the event to the document or a div containing all events and decide on target.

Click count possible with javascript?

Let's say, in website, I want to display the notice message block whenever people click any of the link at my website more than x number of times. Is that possible to count with javascript and display the notice message block ? And can we count the refresh times also ? Or can it be only done with server side language like php ? Please kindly suggest. Thank you.
With Regards,
To do something when any link is clicked is best done with JQuery's live:
Description: Attach a handler to the
event for all elements which match the
current selector, now and in the
future.
$('a').live('click', function() {
// Live handler called.
});
Even if you add more links in run time, this will take care of it.
For counting refreshes I would do it with ajax calls on window.load event, or if you want to use new tech - store it locally with Html5. :-)
You can do that on the client. However, this will be limited to the browser. The simplest will be to store this information in cookies on the client. For instance with jQuery you could simply intercept clicks like that:
$("a").click(function() {
var clickedUrl = $(this).attr('href');
// Here you update the cookie for the count of clicks for that A URL
});
I would either count page refreshes serverside or probably call an ajax function to update the count when the page loads.
If you want to count clicks you may need to bind an event to each link and then for each indivisual button store the number of clicks in global variables...
You could register each click event on the document by using:
$(document).click(function()
{
// Check the number in the cookie and add another
// click to the cookie
});
Then you could use the jQuery cookie plugin to store that value and check it each time there is a click (in the function above).
here's the cookie plugin: https://github.com/carhartl/jquery-cookie
I threw together a quick example. If you're not worried about doing this from page to page then you don't need cookies, just store it in a variable:
http://www.webdesignandseo.net/jquery/clickcount/

Categories

Resources