|
| 1 | +"""Shows how to fetch all cookies, all cookies for |
| 2 | +a given url and how to delete a specific cookie. For |
| 3 | +an example on how to set a cookie see the 'setcookie.py' |
| 4 | +snippet.""" |
| 5 | + |
| 6 | +from cefpython3 import cefpython as cef |
| 7 | + |
| 8 | + |
| 9 | +def main(): |
| 10 | + cef.Initialize() |
| 11 | + browser = cef.CreateBrowserSync( |
| 12 | + url="http://www.html-kit.com/tools/cookietester/", |
| 13 | + window_title="Cookies") |
| 14 | + browser.SetClientHandler(LoadHandler()) |
| 15 | + cef.MessageLoop() |
| 16 | + del browser |
| 17 | + cef.Shutdown() |
| 18 | + |
| 19 | + |
| 20 | +class LoadHandler(object): |
| 21 | + def OnLoadingStateChange(self, browser, is_loading, **_): |
| 22 | + if is_loading: |
| 23 | + print("Page loading complete - start visiting cookies") |
| 24 | + manager = cef.CookieManager.GetGlobalManager() |
| 25 | + # Must keep a strong reference to the CookieVisitor object |
| 26 | + # while cookies are being visited. |
| 27 | + self.cookie_visitor = CookieVisitor() |
| 28 | + # Visit all cookies |
| 29 | + result = manager.VisitAllCookies(self.cookie_visitor) |
| 30 | + if not result: |
| 31 | + print("Error: could not access cookies") |
| 32 | + # To visit cookies only for a given url uncomment the |
| 33 | + # code below. |
| 34 | + """ |
| 35 | + url = "http://www.html-kit.com/tools/cookietester/" |
| 36 | + http_only_cookies = False |
| 37 | + result = manager.VisitUrlCookies(url, http_only_cookies, |
| 38 | + self.cookie_visitor) |
| 39 | + if not result: |
| 40 | + print("Error: could not access cookies") |
| 41 | + """ |
| 42 | + |
| 43 | + |
| 44 | +class CookieVisitor(object): |
| 45 | + def Visit(self, cookie, count, total, delete_cookie_out): |
| 46 | + """This callback is called on the IO thread.""" |
| 47 | + print("Cookie {count}/{total}: '{name}', '{value}'" |
| 48 | + .format(count=count+1, total=total, name=cookie.GetName(), |
| 49 | + value=cookie.GetValue())) |
| 50 | + # Set a cookie named "delete_me" and it will be deleted. |
| 51 | + # You have to refresh page to see whether it succeeded. |
| 52 | + if cookie.GetName() == "delete_me": |
| 53 | + # 'delete_cookie_out' arg is a list passed by reference. |
| 54 | + # Set its '0' index to True to delete the cookie. |
| 55 | + delete_cookie_out[0] = True |
| 56 | + print("Deleted cookie: {name}".format(name=cookie.GetName())) |
| 57 | + # Return True to continue visiting more cookies |
| 58 | + return True |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == '__main__': |
| 62 | + main() |
0 commit comments