【问题标题】:Unable to read cookie in UIWebview browser with document.cookie无法使用 document.cookie 在 UIWebview 浏览器中读取 cookie
【发布时间】:2012-04-04 15:42:48
【问题描述】:

我有一个 iOS 应用程序,我在其中加载 web 视图中的 html 内容。该 html 是一个登录页面,其中用户凭据通过 ajax 发送到服务器并接收到身份验证成功/失败响应。现在,响应包含一个 cookie(在 Set-Cookie 标头字段中),我可以像这样在 Objective-C 端捕获它,

NSDictionary* headers = [(NSHTTPURLResponse *)response allHeaderFields]; 
NSString *strCookies = [headers valueForKey:@"Set-Cookie"]; 
NSLog(@"cookies -> %@", strCookies);

同样的响应还包含我在浏览器中使用的responseText

Ajax("/login", "POST", { onsuccess : function(response){ 
       /* Do HTML stuff with response */ }  
});

现在我需要 cookie 来发出进一步的 ajax 请求(在登录页面之后)。但是,cookie 没有在 webview 浏览器中设置。寻找 document.cookie 返回一个空字符串。我可以使用xhr.getAllResponseHeaders() 打印所有响应标头,但我无法访问xhr 对象中的Set-Cookie 字段。

如何在 webview 中设置 cookie?还是我别无选择,只能通过 Obj-C 发出所有 ajax 请求?

【问题讨论】:

    标签: javascript ios ajax cookies uiwebview


    【解决方案1】:

    您可以在发送到 web 视图的请求中设置 cookie。

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:yourURL];
    [request setValue:yourCookie forHTTPHeaderField:@"Cookie"];
    

    这可以在 UIWebview 委托 shouldStartLoadWithRequest 中完成

    【讨论】:

    • @fenderplayer 这回答了你的问题吗?
    猜你喜欢
    • 2013-04-11
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 2015-01-23
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多