9

I am developing a web bot using WinForms WebBrowser control. Everything is working fine except for the second click() call in following code:

function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();             //<-- This is working
        var x = $('#s_at_m_4-menu li')[5];
        var saveLink = $(x).find('a')[0];
        if (saveLink != null){
            saveLink.click();           //<-- This is not working

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}

saveLink is not null. I know this because I placed an alert() call inside the condition.

Updated code with suggested solutions

function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();
        var x = $('#s_at_m_4-menu li').eq(5);
        var saveLink = x.find('a').eq(0);
        if (saveLink != null) {
            alert(saveLink.html());
            saveLink.click();

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}

But still the same problem. 'alert()' is working fine but html() is showing inner text instead of HTML of the anchor.

HTML Code

<li data-caption="Save Record                [Ctrl+S]" class="sbui-appletmenu-item  ui-menu-item" role="presentation">
<a href="javascript:void(0)" aria-disabled="false" class="ui-corner-all" id="ui-id-254" tabindex="-1" role="menuitem">Save Record                [Ctrl+S]</a>
</li>

ID of the anchor tag is dynamically generated.

Also, click() is triggering when the same code is executed from Google Chrome Console. So, could it be the issue with the WebBrowser control?

Update

I think guys its a problem with the webrowser control that inherits Internet Explorer. So now I am shifting to another browser control and testing the code on it. Will let you know if it works there.

Aishwarya Shiva
  • 3,460
  • 15
  • 58
  • 107
  • What are you expecting saveLink.click() to do? Keep in mind, saveLink there is not a jQuery object. It is the Element since you did [0] instead of eq(0) and click() on a normal Element will not cause any click handlers bound with jQuery to execute. – Taplar May 26 '17 at 15:57
  • To those saying you need to wrap the `saveLink` in `$()`. `.click()` is a DOM function, it is **not** a jQuery function, jQuery has `.click()` to bind an event handler to onclick, i.e. it is short for `.on( "click", )` – Nick is tired May 26 '17 at 15:57
  • @NickA http://api.jquery.com/click/#click The third option of click() does indeed exist in jQuery also. It's a short hand for trigger('click') – Taplar May 26 '17 at 16:00
  • @Taplar except that all it does is call the DOM click function, so not really – Nick is tired May 26 '17 at 16:03
  • Your statement said that jquery did not have a click() method without parameters. But it does. The users confusion about if they have an Element or a JQuery element is irrelivant to that. – Taplar May 26 '17 at 16:03
  • @Taplar no, it doesn't the documentation references it because it already exists, it doesn't implement it – Nick is tired May 26 '17 at 16:04
  • It doesn't reference -it-. It references it's own click() method. That's what i'm saying. Regardless of what that method does, it DOES exist. – Taplar May 26 '17 at 16:05
  • what do you expect saveLink.click() to display? from the html attached it looks like link is set to href='javascript:void(0)'.Can you attach sample html for this? – user1010186 Jun 01 '17 at 13:40
  • @user1010186 it doesn't display anything but just saves some record on the website database. – Aishwarya Shiva Jun 01 '17 at 13:50
  • Web browser control use IE internally, i guess default IE version on your laptop is not latest. check this https://stackoverflow.com/questions/17922308/use-latest-version-of-internet-explorer-in-the-webbrowser-control – user1010186 Jun 01 '17 at 14:19
  • @user1010186 I have a desktop and it has the latest version of Internet Explorer 11 – Aishwarya Shiva Jun 01 '17 at 14:51
  • do you have any event attached to your link, I also see href="javascript:void(0)", it's not the origin of your problem ? – Kashkain Jun 02 '17 at 10:41
  • @Kashkain yes there is an event attached to the link but it's a third party​ site. I can't edit it. I must find a solution with `javascript:void(0)` – Aishwarya Shiva Jun 02 '17 at 10:53
  • did you missed onclick event anchor tag or you bind it dynamically – Asav Vora Jun 03 '17 at 08:20
  • @AishwaryaShiva Try changing `saveLink.click();` to `saveLink.performClick();` – Gururaj Jun 04 '17 at 17:36
  • where does the event binded to menuButton.click(); came from? was it the same source where the binded saveLink.click(); is? – perseusl Jun 06 '17 at 07:06

13 Answers13

1

You have to wrap your object with jQuery in order to make it work:

var saveLink = $($(x).find('a')[0]);
Ursache
  • 196
  • 8
1

Try with Below condition's:

  1. trigger('click') instead of click
  2. Change the if condition validation with if(saveLink) .Its validate both null,undefined all false statement
  3. Return with number=> 0 instead of sting =>'0'
  4. anchor tag redirection use with window.location.href and get the href value from anchor try with attr('href')
function SaveRecordClick() {
  try {
    var menuButton = $('#s_at_m_4');
    menuButton.trigger('click');
    var x = $('#s_at_m_4-menu li').eq(5);
    var saveLink = x.find('a').eq(0);
    if (saveLink) {
      alert(saveLink.html());
      window.location.href=saveLink.attr('href');
     return 1;
    }
  } catch (err) {
    alert(err.message);
  }
  return 0;
}

working example

function SaveRecordClick() {
  try {
    var menuButton = $('#s_at_m_4');
    menuButton.trigger('click');
    var x = $('#s_at_m_4-menu li').eq(5);
    var saveLink = x.find('a').eq(0);
    if (saveLink) {
      alert(saveLink.html());
      window.location.href=saveLink.attr('href');
     return 1;
    }
  } catch (err) {
    alert(err.message);
  }
  return 0;
}
SaveRecordClick()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="s_at_m_4-menu">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li data-caption="Save Record                [Ctrl+S]" class="sbui-appletmenu-item  ui-menu-item" role="presentation">
    <a href="https://example.com" aria-disabled="false" onclick="console.log('s')" class="ui-corner-all" id="ui-id-254" tabindex="-1" role="menuitem">Save Record                [Ctrl+S]</a>
  </li>
  <li></li>
</ul>
prasanth
  • 22,145
  • 4
  • 29
  • 53
0

saveLink will never be null, since find/eq will always return a jQuery object, regardless of whether the element or elements exist or not.

Instead, try using the length property to check for existence:

if (saveLink.length)
budi
  • 6,351
  • 10
  • 55
  • 80
0
function SaveRecordClick() {
    try {
        var menuButton = $('#s_at_m_4');
        menuButton.click();
        var x = $('#s_at_m_4-menu li').eq(5);
        var saveLink = x.find('a').eq(0);
        if (saveLink != null) {
            alert(saveLink.html());
            saveLink.live('click');//Use live click 

            return "1";
        }
    }
    catch (err) {
        alert(err.message);
    }
    return "0";
}
Uday
  • 3
  • 3
  • Not working. `function not found`. And `live()` is deprecated. Most probably removed from the library: http://api.jquery.com/category/removed/ – Aishwarya Shiva Jun 01 '17 at 18:43
0

savelink should be dom element for null check

var saveLink = $(x).find('a:first')[0];

or

var saveLink = $(x).find('a').eq(0)[0];

or

var saveLink = $(x).find('a').first()[0];
Mert Cingoz
  • 732
  • 1
  • 13
  • 12
0

I did not understand Do you need to click or add function in the click?

Add function :

jQuery('teste').click(function(){console.log('teste')});

Click:

jQuery('teste').trigger('click');
0

Teste utilized jQuery.

jQuery(saveLink).click(function(){
console.log('click!');
});
0

try this

$(document).on('click',$(saveLink),function(event){ ///your code })

abelh2200
  • 37
  • 8
  • It's executing the code inside this function on click but not performing original action of the link. I am not trying to bind a new click action to this link instead executing an action on a third party website. The action is to save the record in database of that website. I am developing a bot. – Aishwarya Shiva Jun 01 '17 at 18:11
  • try this then `$(saveLink).click(), put a breakpoint there and see in Watch if saveLink is != of undefined, if it is should work` – abelh2200 Jun 01 '17 at 18:16
  • Breakpoints in JavaScript don't work when you are building a WinForms project. But I checked for `saveLink!=undefined` by executing `alert(saveLink.html())` and it's fetching the HTML successfully. – Aishwarya Shiva Jun 01 '17 at 18:33
0

Your updated code with suggested solutions is good, but the .html() method gets the content of an HTML element. Thus, you need to use saveLink.parent().html() to get outer HTML of the anchor.
If there is other elements in the parent container, you could create temporary element to get only hiperlink HTML:

var anchorHTML = $('<div>').append(saveLink.clone()).html();

To click on saveLink using Javascript try to use x.find('a')[0].click() instead of saveLink.click().
I used URL of your profile in href attribute for visual clarity. If you run the snippet below, then user click on the link will be simulated and your profile page will be displayed.

function SaveRecordClick() {
  try {
    var x = $('#s_at_m_4-menu li').eq(5);
    var saveLink = x.find('a').eq(0);
    if (saveLink != null) {
      var anchorHTML = $('<div>').append(saveLink.clone()).html();
      alert(anchorHTML);
      saveLink[0].click();
      return "1";
    }
  } catch (err) {
    alert(err.message);
  }
  return "0";
}
console.log(SaveRecordClick());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="s_at_m_4-menu">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li data-caption="Save Record                [Ctrl+S]" class="sbui-appletmenu-item  ui-menu-item" role="presentation">
    <a href="https://stackoverflow.com/users/1124494/aishwarya-shiva" aria-disabled="false" class="ui-corner-all" id="ui-id-254" tabindex="-1" role="menuitem">Save Record                [Ctrl+S]</a>
  </li>
  <li></li>
</ul>
Alexander
  • 4,420
  • 7
  • 27
  • 42
  • Ok it works for fetching HTML. But that was just for testing if `saveLink` is `null` or not and it's not. The main objective is to click on `saveLink` using Javascript/JQuery not fetching the HTML. But it's not triggering. – Aishwarya Shiva Jun 02 '17 at 15:32
  • @AishwaryaShiva, I have updated the answer. Try again, please. Has it worked? – Alexander Jun 02 '17 at 17:03
  • @AishwaryaShiva, I have made some modifications in your code and it works. Try to run the snippet from my answer. Maybe I didn't understand what do you want? – Alexander Jun 03 '17 at 03:17
  • @AishwaryaShiva, hasn't you trouble solved? Try to run the snippet, and tell me, please, what does not suit? I can, perhaps, improve it. – Alexander Jun 05 '17 at 04:15
  • @AishwaryaShiva, it is very strange. When I run the snippet the alert box with the `saveLink` outer HTML is displayed. After I click OK button on the alert box your profile page is appear in result window. I don't understand what's your problem, but the example [really works](https://youtu.be/oz4n1J8Mplk). – Alexander Jun 06 '17 at 02:32
  • I think may be it's a problem with internet explorer. I downloaded a new browser control and testing the code on it. If it works there I will let you know. – Aishwarya Shiva Jun 06 '17 at 07:00
0

Best way to fire an event from JavaScript

$( "#ID" ).trigger( "click" ); 

I hope it will work for you.

0

Remember one thing javascript and javascript frameworks are event driven,so please don't try to implement the functional programming concepts

$(document).ready(function(){
   $("#s_at_m_4").click(function(){
   // put your code here   
   });
});
Shubham Bansal
  • 586
  • 6
  • 7
0

What my theory about this is that the click function was not actually bound to the element. This can be due to the html was not yet in the page when the script or binding of click is executed. Try checking the binded click in saveLink.click();

try to make it in the format

$(body).delegate(saveLink, 'click', function() { //try alert here to check });

perseusl
  • 348
  • 1
  • 14
0

Thank you everyone for your answers and comments.

After spending a week in researching the third party website, today I finally found the solution to my problem. Actually the problem was not with JavaScript or HTML but the way the website validate the form I am trying to autofill using my bot.

I awarded bounty to the answer whose conversation in comments gave me some hints.

The click on saveLink was not firing because I was programmatically setting a value of a text box using .val() but for some reason the website was not saving values directly set using this function. But when I changed the value using a combo box that loads value for the textbox from the server (Although the value set from server or using val() function are exactly same.), then the click successfully fired after that.

I also used setTimeout() at various places because the code was executing too fast before the value can be set in some form fields.

So in future if someone faces a similar problem then make sure you study the behavior of the page or form you are trying to submit.

Aishwarya Shiva
  • 3,460
  • 15
  • 58
  • 107