Search code examples
c#winformsf#windowsformsintegration

Getting cookies from WebBrowser in F#/C#


My goal is to retreive the cookies from a webBrowser Control. I tried to do this with a reference, but Event.map doesn't allow me to return the value:

let getCookie(url:string) = 
    let form  = new Form(Text="Internet Navigator")
    form.AutoScaleDimensions <- new System.Drawing.SizeF(6.0F, 13.0F)
    form.AutoScaleMode <- System.Windows.Forms.AutoScaleMode.Font
    form.ClientSize <- new System.Drawing.Size(849, 593)
    form.ResumeLayout(false)
    form.PerformLayout()

    let wb = new WebBrowser()
    wb.Visible<-true
    wb.AutoSize<-true
    wb.Size <- new System.Drawing.Size(804, 800)
    form.Controls.Add(wb)
    form.Show()


    let cookie = ref ""

    wb.Navigate(url)
    wb.DocumentCompleted
    |> Event.map(fun _ -> cookie:= wb.Document.Cookie)
    !cookie

Ideally there is a way to return the cookie value from within the Event.map (or something like that)?


Solution

  • UPDATED : To return cookie value from the function rather than using callback

    let getCookie(url:string) = 
            let form  = new Form(Text="Internet Navigator")
            form.AutoScaleDimensions <- new System.Drawing.SizeF(6.0F, 13.0F)
            form.AutoScaleMode <- System.Windows.Forms.AutoScaleMode.Font
            form.ClientSize <- new System.Drawing.Size(849, 593)
            form.ResumeLayout(false)
            form.PerformLayout()
    
            let wb = new WebBrowser()
            wb.Visible<-true
            wb.AutoSize<-true
            wb.Size <- new System.Drawing.Size(804, 800)
            form.Controls.Add(wb)
            wb.DocumentCompleted |> Event.add (fun _ -> form.Close())
            wb.Navigate(url)
            form.ShowDialog() |> ignore
            wb.Document.Cookie
    
    [<STAThreadAttribute>]
    do
        let cookie = getCookie "http://www.google.com"
        Console.Read() |> ignore