Firefox 在安裝完成的時候,會問你要不要匯入其它瀏覽器的資料,比如說匯入 IE 的 cookie, history 之類。匯入的代碼在
browser/components/migration/src/nsIEProfileMigrator.cpp
其中,匯入 cookie 的代碼是:
/* Fetch and translate the current user's cookies.<br /> Return true if successful. */<br />nsresult<br />nsIEProfileMigrator::CopyCookies(PRBool aReplace)<br />{<br /> // IE cookies are stored in files named <username>@domain[n].txt<br /> // (in <username>'s Cookies folder. isn't the naming redundant?)<br /> nsresult rv = NS_OK;<br />...</p><p> return rv;<br />}<br />
這部分代碼很長,我就不完整地貼在這裡了。大體上就是想辦法找到 IE 儲存 cookie 檔案的路徑,其中 Vista 如果開啟了 UAC 位置還不一樣,還要分別作判斷,然後把檔案一個一個讀進來。這樣的實現其實並不完美。Win32 已經提供了一條現成的 API:
HANDLE FindFirstUrlCacheEntry(<br /> __in LPCTSTR lpszUrlSearchPattern,<br /> __out LPINTERNET_CACHE_ENTRY_INFO lpFirstCacheEntryInfo,<br /> __inout LPDWORD lpcbCacheEntryInfo<br />);<br />
其中第一個參數如果設定為 "cookie:" 的話,就可以枚舉出所有儲存的 cookie. 這個 api 從 Windows 2000 開始就提供了,而 Windows 2000 也是 Firefox 所支援的最低版本的 Windows,所以沒有相容性的問題。
用好 Win32 API,往往可以起到事半功倍的效果。