You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Reacted by Nikita Nemkin, ShaunLoganOracle, Antti Järvinen, Dav-id, MysteriousGreenBean, Brandon, Pharmhaus.Net, Vijay Meganathan, John Schroedl and chzuping
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.
Reacted by David Risney, Edward Chan Jia Wei and znakeeye
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:
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.
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);
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:
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.
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
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.
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:
user runs our app with embedded webview
user navigates to a web site with a login using webview
website login returns authentication cookie
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.
Reacted by ShaunLoganOracle, David Risney and 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).
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.
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.
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.
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.
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
Activity
david-risney commentedon May 7, 2019
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.
david-risney commentedon May 7, 2019
Can you say what you would want to use this API for? Is it managing auth related cookies?
MichaelKetting commentedon May 7, 2019
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.
edwardchanjw commentedon Jun 2, 2019
Hopefully support all under Chrome's Dev Tools's Application Storage. But the highlighted 3 hopefully be there.
verelpode commentedon Aug 19, 2019
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:
HttpBaseProtocolFilter.CookieManagerwhen using a separate-process mode in WebView.verelpode commentedon Aug 20, 2019
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-cookieheaders 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.HttpClientto download a related URL from the same website, the website may reject theHttpClientbecause of missing cookies -- the website requires its session cookies for security/auth reasons, but these cookies are only available in WebView2 and not inHttpClient. Thus we need aGetCookiesmethod in WebView2 that allows us to retrieve all of the cookies, and then our app will be able to insert those cookies intoHttpClientor ratherWindows.Web.Http.HttpCookieManager. Thus aGetCookiesmethod makes it possible to bridge the gap between WebView2 andHttpClient.Although I mentioned
Windows.Web.Http.Filters.HttpBaseProtocolFilter.CookieManagerin my previous message, it's not essential to make WebView2 directly or automatically compatible withHttpBaseProtocolFilter.CookieManager. WebView2 can be independent ofHttpBaseProtocolFilterandHttpClient. The core thing that is really needed is aGetCookiesmethod in WebView2, and then apps can transfer this cookie data into any other relevant services (such asHttpClient) by themselves.verelpode commentedon Aug 26, 2019
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:
Interface
IWebView2HttpCookieCollectionwould be approximately the C++/COM equivalent of Windows.Web.Http.HttpCookieCollection.Each cookie in the
IWebView2HttpCookieCollectionwould be an instance of interfaceIWebView2HttpCookie, which would be the C++/COM equivalent of Windows.Web.Http.HttpCookie. ThusIWebView2HttpCookiewould contain members equivalent to the following methods ofWindows.Web.Http.HttpCookie:In our environment, it's much less important to support
put_Cookiesthanget_Cookies, but still desirable.get_Cookiessolves the problem where WebView2 is used first, followed byWindows.Web.Http.HttpClient, but what about the reverse order? In situations whereHttpClientis used first, followed by WebView2, ideally WebView2 would supportput_Cookiesin order to copy cookies fromHttpClientto WebView2. Thus I suggest thatIWebView2WebViewbe given both of:put_Cookieswould 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:If it's too difficult to support all of those, then at least the
get_Cookiesalone would be a big relief in our case.[-]Support for getting and setting the cookies for the current page[/-][+]Support for getting and setting the cookies[/+]michalkania commentedon Nov 30, 2019
I would like to point out that
Windows.Web.Http.HttpClientis Windows specific and it can share resources ofWindows.Web.Http.HttpCookieManagerin 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.HttpClientis 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 ourSystem.Net.CookieContaineror evenSystem.Net.Http.HttpClientto get this feeling of howWindows.Web.Http.HttpClientis working on Windows with WebView.dd8 commentedon Apr 26, 2020
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:
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.romanov commentedon May 21, 2020
Any updates?
david-risney commentedon May 21, 2020
Nothing concrete to report yet. But cookie management is a popular feature request and one we will be looking into.
angshuman-agarwal commentedon May 24, 2020
Make it like
CEF- https://github.com/cefsharp/CefSharp/blob/master/CefSharp.Core/CookieManager.hpipalot commentedon Jun 19, 2020
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:
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.
30 remaining items
champnic commentedon Jan 30, 2021
This is now available in our latest release package 1.0.705.50. Thanks!
https://docs.microsoft.com/en-us/microsoft-edge/webview2/reference/win32/icorewebview2cookiemanager?view=webview2-1.0.705.50&preserve-view=true
markismail7 commentedon Jul 9, 2021
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.
champnic commentedon Jul 9, 2021
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
markismail7 commentedon Jul 9, 2021
Is there an example on how to set WebView2 folder ?
champnic commentedon Jul 9, 2021
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.markismail7 commentedon Jul 9, 2021
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.
shyjusachin commentedon Jan 3, 2022
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
2.Setting headers in CoreWebView2_WebResourceRequested
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.
champnic commentedon Jan 6, 2022
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
shyjusachin commentedon Jan 7, 2022
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
champnic commentedon Jan 7, 2022
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/
thepwrtank18 commentedon Apr 10, 2022
Is there any way to get (not set) a cookie from the WebView2 instance?
ShaunLoganOracle commentedon Apr 11, 2022
Are you looking for this API? https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2cookiemanager?view=webview2-dotnet-1.0.1150.38
shyjusachin commentedon Apr 11, 2022
ShaunLoganOracle TheTank20 (@thepwrtank18) Yes you can use any of it based on your requirement
eg :
Await WebView21.CoreWebView2.CookieManager.GetCookiesAsync(uri)MadHatterENV commentedon Jun 29, 2022
Thanks; i'll will have a look into this.
Kind Regards :)