Skip to content

Support for getting and setting the cookies #4

Closed

Description

I looked at the API docs (https://docs.microsoft.com/en-us/microsoft-edge/hosting/webview2/reference/iwebview2webview) but didn't see find a matching API, so here's the feature request:

It would be great to be able to get and set the cookies used by the WebView. Internet Explorer allows getting the cookies by calling InternetGetCookieEx() from wininet.dll.

With this feature you build an application that uses both the browser control and a side channel when interacting with a website.

Edit: Possibly, the WebResourceRequested event might allow access via the raw headers from the GetResponse method (https://docs.microsoft.com/en-us/microsoft-edge/hosting/webview2/reference/iwebview2webresourcerequestedeventargs#interface_i_web_view2_web_resource_requested_event_args) but that's quite the effort.

AB#27223320

Activity

  1. david-risney commented on May 7, 2019

    @david-risney
    Contributor

    Yes, the WebResourceRequested event might work as a work around but it is not ideal. I'll make sure cookies are on our backlog for APIs. Thanks.

  2. david-risney commented on May 7, 2019

    @david-risney
    Contributor

    Can you say what you would want to use this API for? Is it managing auth related cookies?

  3. MichaelKetting commented on May 7, 2019

    @MichaelKetting
    Author

    David Risney (@david-risney) yes, mainly auth- and session cookies. Basically, whenever you build a desktop application that hosts the browser control to interact with a specific known site (or web application product) and you also need to do some out-of-band communication stuff, e.g. uploading/downloading content or doing status messages, calling web services, etc, you need to be able to share the authentication data.

    One example would be to build a rich-client desktop integration for an issue tracker or build server, where you can login to the web server and then also are able to expose the attachements or build artifacts directly to the desktop.

  4. edwardchanjw commented on Jun 2, 2019

    @edwardchanjw

    Hopefully support all under Chrome's Dev Tools's Application Storage. But the highlighted 3 hopefully be there.

    1. Local Storage
    2. Session Storage
    3. IndexedDB
    4. Web SQL
    5. Cookie
  5. verelpode commented on Aug 19, 2019

    @verelpode

    Yes please! It's very important to improve the ability to list, read, set, and clear cookies, especially when WebView2 uses a separate-process mode, and it is a major problem currently! Please see my explanation in the section "Inability to download PDF files because of cookie access failure" in issue #38.

    Although the following cookie issues are in the repo for WPF WebView 1, these same problems are also applicable to WebView2. When designing WebView2, we would greatly appreciate it if you could solve these cookie difficulties:

  6. verelpode commented on Aug 20, 2019

    @verelpode

    WebResourceRequested usually doesn't work for reading cookies because IWebView2WebResourceRequestedEventArgs.Response is always null because it's not intended for apps to read, rather it's intended for apps to intercept a Request and generate a different Response. To collect cookies, you'd typically need to look for set-cookie headers in the Response not in the Request, but WebResourceRequested actually only gives you access to the Request, not the Response. Hence the name is "WebResourceRequested" not "WebResourceResponded".

    When a website is viewed in WebView2 and then you try to use Windows.Web.Http.HttpClient to download a related URL from the same website, the website may reject the HttpClient because of missing cookies -- the website requires its session cookies for security/auth reasons, but these cookies are only available in WebView2 and not in HttpClient. Thus we need a GetCookies method in WebView2 that allows us to retrieve all of the cookies, and then our app will be able to insert those cookies into HttpClient or rather Windows.Web.Http.HttpCookieManager. Thus a GetCookies method makes it possible to bridge the gap between WebView2 and HttpClient.

    Although I mentioned Windows.Web.Http.Filters.HttpBaseProtocolFilter.CookieManager in my previous message, it's not essential to make WebView2 directly or automatically compatible with HttpBaseProtocolFilter.CookieManager. WebView2 can be independent of HttpBaseProtocolFilter and HttpClient. The core thing that is really needed is a GetCookies method in WebView2, and then apps can transfer this cookie data into any other relevant services (such as HttpClient) by themselves.

  7. verelpode commented on Aug 26, 2019

    @verelpode

    The cookie problem is our highest priority currently -- it is a major problem in our environment. Would it be helpful if I start discussing the precise details of the proposed cookie API? I suggest adding to IWebView2WebView:

    public HRESULT get_Cookies(IWebView2HttpCookieCollection ** value);
    

    Interface IWebView2HttpCookieCollection would be approximately the C++/COM equivalent of Windows.Web.Http.HttpCookieCollection.

    Each cookie in the IWebView2HttpCookieCollection would be an instance of interface IWebView2HttpCookie, which would be the C++/COM equivalent of Windows.Web.Http.HttpCookie. Thus IWebView2HttpCookie would contain members equivalent to the following methods of Windows.Web.Http.HttpCookie:

    string Domain { get; }
    string Path { get; }
    string Name { get; }
    string Value { get; set; }
    System.DateTimeOffset? Expires { get; set; }
    bool HttpOnly { get; set; }
    bool Secure { get; set; }
    

    In our environment, it's much less important to support put_Cookies than get_Cookies, but still desirable. get_Cookies solves the problem where WebView2 is used first, followed by Windows.Web.Http.HttpClient, but what about the reverse order? In situations where HttpClient is used first, followed by WebView2, ideally WebView2 would support put_Cookies in order to copy cookies from HttpClient to WebView2. Thus I suggest that IWebView2WebView be given both of:

    public HRESULT get_Cookies(IWebView2HttpCookieCollection ** value);
    public HRESULT put_Cookies(IWebView2HttpCookieCollection * value);
    

    put_Cookies would replace all cookies in WebView2, thus it would also delete cookies (in the normal manner of replacing the contents of a collection).

    I also suggest making the following methods in IWebView2WebView:

    // Add or replace (but not delete) multiple cookies in WebView2:
    public HRESULT AddOrReplaceCookies(IWebView2HttpCookieCollection * cookies);
    
    // Add or replace one cookie in WebView2:
    // This could be named "SetCookie" or "AddOrReplaceCookie":
    public HRESULT SetCookie(IWebView2HttpCookie * cookie);
    
    // Delete one cookie:
    public HRESULT DeleteCookie(LPCWSTR domain, LPCWSTR path, LPCWSTR name);
    // Alternatively:
    public HRESULT DeleteCookie(IWebView2HttpCookie * cookie);
    
    // Delete all cookies in the WebView2:
    public HRESULT DeleteAllCookies();
    
    // Get one cookie by name (exact match of domain, path, name):
    // Output is null if no matching cookie is found:
    public HRESULT GetCookie(LPCWSTR domain, LPCWSTR path, LPCWSTR name, IWebView2HttpCookie ** outCookie);
    
    // Get all cookies for the specified domain:
    // Matches any value of `HttpCookie.Path` and `HttpCookie.Name`:
    public HRESULT GetCookies(LPCWSTR domain, IWebView2HttpCookieCollection ** outCookies);
    

    If it's too difficult to support all of those, then at least the get_Cookies alone would be a big relief in our case.

  8. changed the title [-]Support for getting and setting the cookies for the current page[/-] [+]Support for getting and setting the cookies[/+] on Nov 29, 2019
  9. michalkania commented on Nov 30, 2019

    @michalkania

    I would like to point out that Windows.Web.Http.HttpClient is Windows specific and it can share resources of Windows.Web.Http.HttpCookieManager in WebView on Windows, but as Verel Pode (@verelpode) mentioned, it doesn't have to work that way with WebView2.

    Anyway what about other platforms?

    With Xamarin and .Net Core System.Net.Http.HttpClient is probably the way to go. It already is done with multiple frameworks in mind. Making WebView2 share common classes would be desirable. Maybe there could be a way to pass a reference of our System.Net.CookieContainer or even System.Net.Http.HttpClient to get this feeling of how Windows.Web.Http.HttpClient is working on Windows with WebView.

  10. dd8 commented on Apr 26, 2020

    @dd8

    We also have a requirement for this. We need to get customisation/authentication cookies on a per URL basis to send in web crawler requests. Use case:

    1. user runs our app with embedded webview
    2. user navigates to a web site with a login using webview
    3. website login returns authentication cookie
    4. user then starts scan of site with embedded crawler which adds cookies to HTTP requests (this allows sites with logins to be scanned)

    On macOS we use [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url]. This API works well - the calling code doesn't need to worry about cookie domain, path or expiry, or whether the cookie is temporary or persistent.

  11. romanov commented on May 21, 2020

    @romanov

    Any updates?

  12. david-risney commented on May 21, 2020

    @david-risney
    Contributor

    Nothing concrete to report yet. But cookie management is a popular feature request and one we will be looking into.

  13. pipalot commented on Jun 19, 2020

    @pipalot

    I also need cookie management so that I can add an auth cookie to the request being sent to the website I am navigating to.

    It has been suggested in this discussion that it might be possible to set cookies in the WebResourceRequested event, but there seems to be a bug in WebResourceRequested that ignores attempts to set the headers (despite the documentation saying you can do it).

    For example, this fails to add a cookie:

           private void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
            {
                    e.Request.Headers.Add("Cookie", "cookieName=cookieValue");
            }
    

    Another example of WebResourceRequested failing to allow headers to be set, this time involving trying to set the Authentication property:
    https://stackoverflow.com/questions/62094181/edit-http-request-header-with-webview2

    If you inspect the headers immediately after trying to set them, you will see that nothing has been set.

    So I think we must wait for a cookie management feature to be added to WebView2, or the bugs in WebResourceRequested to be fixed.

    Is there any estimate of when either of those is likely to be addressed please? Many thanks.

  14. 30 remaining items

  15. markismail7 commented on Jul 9, 2021

    @markismail7

    I have click once application that uses webview2 and every time the user update the app, the application deletes the cookies. I checked the folder for webview2 and sure the cookies are deleted. How can i prevent that from happening during an update.

  16. champnic commented on Jul 9, 2021

    @champnic
    Member

    Hey Mark Ismail (@markismail7) - The cookies are tied to a User Data Folder. The default location for that folder is next to the exe, so likely as ClickOnce is updating it's deleting that folder and you lose cookies. To get around this, can you try specifying a different location for the User Data Folder when initializing the WebView2? More info:
    https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/user-data-folder

  17. markismail7 commented on Jul 9, 2021

    @markismail7

    Hey Mark Ismail (@markismail7) - The cookies are tied to a User Data Folder. The default location for that folder is next to the exe, so likely as ClickOnce is updating it's deleting that folder and you lose cookies. To get around this, can you try specifying a different location for the User Data Folder when initializing the WebView2? More info:
    https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/user-data-folder

    Is there an example on how to set WebView2 folder ?

  18. champnic commented on Jul 9, 2021

    @champnic
    Member

    Assuming you are using .NET (the Win32 pattern is similar) you can set the user data folder when creating the environment:
    https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2environment.createasync?view=webview2-dotnet-1.0.864.35

    And use this environment object to call WebView2.EnsureCoreWebView2Async(environment). Note that you should remove setting the Source property to initialize the control, because that will initialize the control with a default environment before you can call Ensure... yourself.

  19. markismail7 commented on Jul 9, 2021

    @markismail7

    use this environment object to call WebView2.EnsureCoreWebView2Async(environment). Note that you should remove setting the Source property to initiali

    I really appreciate the response here.
    I'm using VB.net.
    I tried this
    Private Async Sub InitializeBrowser(ByVal Optional url As String = Nothing)
    Dim userDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\VSMFolder\Web"
    Dim env = Await CoreWebView2Environment.CreateAsync(Nothing, userDataFolder)
    Await WebView.EnsureCoreWebView2Async(env)
    WebView.Source = New Uri(url)
    End Sub
    I called InitializeBrowser(url) on loading the form that contains webview2 .

    It didn't do anything. I've been working on this for hours now. The only way around it for me, is to copy the folder before updating and paste it back after updating. I wish it was easier than that. I was looking into it over the web. Alot of people are struggling to do this.

  20. shyjusachin commented on Jan 3, 2022

    @shyjusachin

    Nic Champagne Williamson [MSFT] (@champnic) Hi here I can see that set cookies in WebVeiw2 is resolved. But here I am still failed to set the cookies through webresourcerequested event handler. Correct me if I made any mistakes in my code, using VB.net and Webview version is 1.0.1020.30

    1.Initialized handler in CoreWebView2InitializationCompleted

    Private Sub WebView21_CoreWebView2InitializationCompleted(sender As Object, e As Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs) Handles WebView21.CoreWebView2InitializationCompleted
    
            WebView21.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All)
            AddHandler WebView21.CoreWebView2.WebResourceRequested, AddressOf CoreWebView2_WebResourceRequested
        End Sub
    

    2.Setting headers in CoreWebView2_WebResourceRequested

    Private Sub CoreWebView2_WebResourceRequested(sender As Object,
        e As CoreWebView2WebResourceRequestedEventArgs)
            e.Request.Headers.SetHeader("Cookie", "cea-token=12345")
            e.Request.Headers.SetHeader("Test", "cea-ssa=123")
    End Sub
    

    While loading CoreWebView2_WebResourceRequested is firing and these headers are setting there
    But once the page is loaded in WebVeiw2 control, seems like cookies are empty, I couldn't find any of these cookies.
    Please correct me if I a wrong in something or should I attempt some different approaches.

    Thanks in advance.

  21. champnic commented on Jan 6, 2022

    @champnic
    Member

    Hey shyjusachin - This function will only set the cookie as a header when sending a request to the server. It is not saving the cookie locally. You can use the cookie APIs if you want to do that:
    https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.cookiemanager?view=webview2-dotnet-1.0.1054.31#Microsoft_Web_WebView2_Core_CoreWebView2_CookieManager

  22. shyjusachin commented on Jan 7, 2022

    @shyjusachin

    Thank you Nic Champagne Williamson [MSFT] (@champnic) for the quick reply. As per your response what I understood is based on my above code, it will send whatever the Cookies required for the domain. Here I am not used CookieManager Api so that it will not save into local storage.

    Still my webview functionality is not working as expected, even here I am sending cookies with the header, url is redirected to login page due to lack of cookies availability.
    Could you please let me know what will the cause here, or how should I ensure cookies are available once the page is loading.

    Please let me know any more information required my side. Expecting your feedback on it. Thank you

  23. champnic commented on Jan 7, 2022

    @champnic
    Member

    This sounds like it might be a mismatch between what is being sent as a cookie, and what the server is expecting. You can verify what cookies are being sent by looking in the DevTools Network tab, or by looking at a NetLog:
    https://textslashplain.com/2020/01/17/capture-network-logs-from-edge-and-chrome/
    https://textslashplain.com/2020/04/08/analyzing-network-traffic-logs-netlog-json/

  24. thepwrtank18 commented on Apr 10, 2022

    @thepwrtank18

    Is there any way to get (not set) a cookie from the WebView2 instance?

  25. shyjusachin commented on Apr 11, 2022

    @shyjusachin

    ShaunLoganOracle TheTank20 (@thepwrtank18) Yes you can use any of it based on your requirement

    eg : Await WebView21.CoreWebView2.CookieManager.GetCookiesAsync(uri)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions