简体   繁体   中英

How to click on link in awesomium webcontrol c#

I have a website that have two links in a div. I want to click on second link which is inside that div. Here is how website's HTML look like:

<div class="title-nav-single">
    <strong></strong>
    <a href="http://www.website.com/50665">Previous</a>
    <a href="http://www.website.com/50665/3">Next</a>
</div>

Now I'm trying to click on the link that contains Next . I don't want to get link href value, I just want to click on the link. Here is what I have tried so far:

private void button1_Click(object sender, EventArgs e)
{
    string xpath = GetJsSingleXpathString("//DIV[@ID=\"outbrain_widget_0\"]/preceding-sibling::DIV[3]//A[normalize-space()=\"Next\"]");
    JsFireEvent(xpath, "click");
    // webcontrol.ExecuteJavascriptWithResult("document.getElementsByClassName('title-nav-single').ElementAt(1).DomObject.click();");
}

public static string GetJsSingleXpathString(string xpath)
{
    return String.Format("document.evaluate(\"{0}\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue", xpath);
}

// executes javascript which fires specified event on element 
// Example: JsFireEvent("document.getElementById('my_id')", "click");
public void JsFireEvent(string getElementQuery, string eventName)
{
    webcontrol.ExecuteJavascript(@"function fireEvent(element,event) {
        var evt = document.createEvent('HTMLEvents');
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        element.dispatchEvent(evt);
    }" + String.Format("fireEvent({0}, '{1}');", getElementQuery, eventName));
}
}

To detect if link was clicked you need to add target="_blank" :

<a href="http://www.website.com/50665/3" target="_blank">Next</a>

and capture this event:

webControl.ShowCreatedWebView += OnShowNewView;

internal static void OnShowNewView( object sender, ShowCreatedWebViewEventArgs e )
{
    // Do sth with your link. it's in e.TargetURL
}

finally, you can open it with traditional way:

System.Diagnostics.Process.Start(e.TargetURL.ToString());

..or do whatever else you want to do with it. More information you can find here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM