StanOverflow
StanOverflow

Reputation: 567

Get attribute value from HTML element in WebBrowser

I need the number in brackets, in this case "14" so that I can send it to a JavaScript function on the page to submit or alternatively is there a way to 'click' the button "Current week"?

<form id="timetablesForm" action="timetablesController.jsp" method="post">
    <p>
        <input type="button" name="Current week" value="Current week" onclick="javascript:void+displayTimetable('14')" />
        <input type="button" name="Next week" value="Next week" onclick="javascript:void+displayTimetable('15')" />
        <input type="button" name="Current semester" value="Semester 1" onclick="javascript:void displayTimetable('7;8;9;10;11;12;13;14;15;16;17;21')" />
    </p>

function displayTimetable(selectdweeks)

I'm working in Windows Phone so the WebBrowser.Document isn't available. I've used the script below to set a value in a different form:

webBrowser1.InvokeScript("eval", "document.getElementById('loginform1').user.value = 'username';");

How do I get a value from the HTML page? What other function can I call with InvokeScript? Appreciate it if you can point me at a list of functions.

Upvotes: 1

Views: 6569

Answers (3)

StanOverflow
StanOverflow

Reputation: 567

Use this

webBrowser1.SaveToString()

Then parse the HTML to get the bit I want

Upvotes: 2

Heinrich Ulbricht
Heinrich Ulbricht

Reputation: 10372

The following code extracts the "14" from your first input "Current week":

private void button1_Click(object sender, RoutedEventArgs e)
{
    // first define a new function which returns the content of "onclick" as string
    webBrowser1.InvokeScript("eval", "this.newfunc_getmyvalue = function() { return document.getElementById('Current week').attributes.getNamedItem('onclick').value; }");
    // now invoke the function and save the result (which will be "javascript:void+displayTimetable('14')")
    string onclickstring = (string)webBrowser1.InvokeScript("newfunc_getmyvalue");
    // now split the string at the single quotes (you might have to adapt this parsing logic to whatever string you expect; this is just a simple approach)
    string[] substrings = Regex.Split(onclickstring, "'");
    // this shows a messagebox saying "14"
    MessageBox.Show(substrings[1]);
}

A little background:

Initially I thought that returning a value should be as easy as:

// ATTENTION: THIS DOESN'T WORK
webBrowser1.InvokeScript("eval", "return 'hello';");

But this always throws a SystemException ("An unknown error has occurred. Error: 80020101.") This is the reason why the code above first defines a JavaScript function which returns the desired value. Then we call this function and the result is returned successfully.

Upvotes: 1

Alex Turpin
Alex Turpin

Reputation: 47776

Have you tried doing just that, getting the value?

Object val = webBrowser1.InvokeScript("eval", "document.getElementById('loginform1').user.value;");

Upvotes: 0

Related Questions