【问题标题】:Cannot add cookie through an iframe无法通过 iframe 添加 cookie
【发布时间】:2014-12-24 04:04:15
【问题描述】:

我正在动态创建一个带有表单的 iframe 并像这样提交此表单:

var iframe = $("<iframe id='download_iframe' style='display: none' src='about:blank'></iframe>");
//...building that form...
form.appendTo( iframe.contents().find('body') ).submit();

在该请求所在的 url,我正在生成一个文件并设置一个像这样的 cookie:

HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
//...setting content type, disposition and etc...
response.Headers.AddCookies(new[]
                                    {
                                        new CookieHeaderValue("ajaxFileDownload", "true")
                                        {
                                            Expires = DateTimeOffset.Now.AddDays(1),
                                            Domain = Request.RequestUri.Host,
                                            Path = "/",
                                            HttpOnly = false
                                        }
                                    });

所以我希望在文件下载开始后设置 cookie,我可以在标题中看到 Set-Cookie

Cache-Control:private
Content-Disposition:attachment; filename=engagement_list_28-10-2014.pdf
Content-Length:60027
Content-Type:application/pdf
Date:Tue, 28 Oct 2014 16:12:09 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/7.5
Set-Cookie:ajaxFileDownload=true; expires=Wed, 29 Oct 2014 16:59:35 GMT; domain=localhost; path=/
X-AspNet-Version:4.0.30319
X-MiniProfiler-Ids:["a8e9bef2-d31e-4f41-8896-9222d880544f"]
X-Powered-By:ASP.NET
X-Powered-By:ARR/2.5
X-Powered-By:ASP.NET

但是document.cookie$("#download_iframe").contents()[0].cookie 是空的,我什至看不到浏览器资源中的cookie。我做错了什么?

【问题讨论】:

    标签: javascript c# iframe cookies asp.net-web-api


    【解决方案1】:

    这可能是由于创建 iframe 的页面是从 localhost 以外的主机加载的。正在为 localhost 创建 cookie,如果您创建的 HTML 是从文件系统或其他主机加载的,您将无法看到 cookie。

    其他原因可能是

    1) 您浏览器的 cookie 政策。

    2) 浏览器运行的操作系统时间。它是否大于 Expires 字段?

    【讨论】:

    • 页面about:blank会导致跨域问题吗?我不确定该页面是如何工作的。
    猜你喜欢
    • 2014-09-11
    • 2011-09-13
    • 2022-09-25
    • 1970-01-01
    • 2018-06-05
    • 2015-07-29
    • 1970-01-01
    • 2021-07-24
    • 2014-12-11
    相关资源
    最近更新 更多