Like many people, it seems like I’ve been working on an application for Windows Phone 7 that integrates with Facebook. Now that I’m getting close to completion, I was looking at the use cases that fall outside of the core area such as logging out of Facebook to enable the user to use different credentials. Traditionally, you’d get the cookies for the relevant Facebook URLs and clear them out. Many people on the forums appear to have hit the same problem that I did in that there are no direct API in Windows Phone 7 to access cookies for the WebBrowser control. I managed to find a way around this and here’s how I did it:
Keeping Track of Cookies
There’s no direct API to get the cookies for the WebBrowser control, but you can get access to the cookies for a specific web request by providing a value for the CookieContainer property:
1: private HttpWebRequest _webRequest;
2: private CookieContainer _cookieContainer = new CookieContainer();
4: this._webRequest = (HttpWebRequest)HttpWebRequest.Create(uri);
5: this._webRequest.CookieContainer = this._cookieContainer;
What you’ll notice here is that I’m creating an HttpWebRequest and an associated CookieContainer and passing that CookieContainer to the web request. What you’ll need to do is to keep hold of this web request for the lifetime of your application, or at the very least keep hold of the last web request that you used to access Facebook (depending on how busy your application is and what you’re doing with web requests. I managed to change my application code to use a single web request for the whole application lifetime). Then you can use the CookieContainer instance to find the relevant cookies.
Finding and Clearing Facebook’s Cookies
In order to track down Facebook’s cookies so that you can clear them out, you need to ask the CookieContainer for the cookies that match a certain URL. I found that asking for https://login.facebook.com/login.php was all I needed to do, but your mileage may vary. I use this code in my
WebClientHelper class (which holds my web request) to clear cookies for a specified URL:
1: public void ClearCookies(Uri uri)
3: var cookies = this._cookieContainer.GetCookies(uri);
4: foreach (Cookie cookie in cookies)
6: cookie.Discard = true;
7: cookie.Expired = true;
I found that setting both the Discard and Expired properties to
true was sufficient to clear the cookies. It may well be that either one of them on their own is adequate; I haven’t had the opportunity to verify that.
So, the code that calls this method looks like this:
1: private static readonly Uri FacebookCookieUri =
If you then send the WebBrowser control to the login URL for Facebook as you would normally, then you should find that the cookies are cleared and the user is presented with the login dialog as usual.
I hope this helps.