Wednesday, February 22, 2006

Posting data with TWebbrower

With a TWebbrowser component it is possible to post data to a webpage. Suppose you have an application with a webbrowser and your application requires a login, and the website also uses a login. The user should now login twice. And that is just to much!

You can however post data to the website with the Navigate method of the webbrowser component.
The declaration of the method is as follows:

procedure Navigate(const URL: WideString; var Flags: OleVariant;
var TargetFrameName: OleVariant;
var PostData: OleVariant); overload;

The last parameter PostData can be used to transfer the login information to the webpage, as if the user pressed the login button of the login form.

procedure LoginWithPostData(AUserName:String;
APassWord:String; LoginUrl:String; AWebBrowser:TWebBrowser);
varPostData, varHeader : OleVariant ;
x : variant;
postdata : string;
arPostdata : array of byte;
i,l: integer;
bch : byte;

postdata := 'UserCode='+AUserName+'&PassWord='+APassWord;
SetLength(arPostdata, Length(PostData));
for i := 1 to Length(postdata) do begin
arPostdata[i-1] := Ord(postdata[i]);
varPostData := arPostdata;
varHeader :=
'Content-Type: application/x-www-form-urlencoded\r\n';
varPostdata, varHeader);

Step 1: Create a string with the postdata
Step 2: Fill an array of byte with the string characters.
Step 3: Assign the array to an OleVariant.
Step 4: Set the appropriate encoding to a OleVariant (varHeader)
Step 5: Navigate the browser.

You should be logged in now!

You could of course also do it the other way around, log in the webbrowser and read the postdata from the BeforeNavigate event. (Just posted by your user and on its way to the webserver)
The disadvantage with this method is that you should parse the postdata string to get the username and you should somehow find out if the user was autorised by the webpage. One way to achieve it is to check the url in the NavigateComplete event of the browser to be the protected url (Page). If the protected page is loaded the user should be logged in and you can then login your application.
The first method, posting the data to the webserver from your application is however the best one.

No comments:

Use an image as your UIBarButtonItem

Using an image as your UIBarButtonItem in your navigationcontroller bar can only be achieved by using a common UIButton as the BarButtonItem...