我正在动态创建一个带有表单的 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,并且我可以在 header 中看到 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资源。我做错了什么?
最佳答案
这可能是由于创建 iframe 的页面是从 localhost 以外的主机加载的。正在为 localhost 创建 cookie,如果您创建的 HTML 是从文件系统或其他主机加载的,您将无法看到 cookie。
可能是其他原因
1) 您的浏览器的 cookie 策略。
2) 浏览器运行的操作系统的时间。它是否大于 Expires 字段?
关于javascript - 无法通过 iframe 添加 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26613617/