Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(637)

Side by Side Diff: ios/web/web_state/js/crw_js_post_request_loader.mm

Issue 1516303002: Adds support for POST request with bodies on WKWebView. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@2564
Patch Set: Created 5 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #import "ios/web/web_state/js/crw_js_post_request_loader.h"
6
7 #include "base/json/string_escape.h"
8 #import "base/mac/scoped_nsobject.h"
9 #import "base/strings/sys_string_conversions.h"
10 #import "ios/web/web_state/js/page_script_util.h"
11 #import "ios/web/web_state/ui/crw_wk_script_message_router.h"
12
13 namespace {
14
15 // Escapes characters and encloses given string in quotes for use in JavaScript.
16 NSString* EscapeAndQuoteStringForJavaScript(NSString* unescapedString) {
17 std::string string = base::SysNSStringToUTF8(unescapedString);
18 return base::SysUTF8ToNSString(base::GetQuotedJSONString(string));
19 }
20
21 // JavaScript message handler name installed in WKWebView for request errors.
22 NSString* const kErrorHandlerName = @"POSTErrorHandler";
23
24 // JavaScript message handler name installed in WKWebView for successful
25 // request completion.
26 NSString* const kSuccessHandlerName = @"POSTSuccessHandler";
27
28 } // namespace
29
30 @interface CRWJSPOSTRequestLoader () {
31 base::scoped_nsobject<NSString> _requestScript;
32 }
33
34 // JavaScript used to execute POST requests. Lazily instantiated.
35 @property(nonatomic, copy, readonly) NSString* requestScript;
36
37 // Handler for UIApplicationDidReceiveMemoryWarningNotification.
38 - (void)handleMemoryWarning;
39
40 // Forms a JavaScript method call to |requestScript| that executes given
41 // |request|.
42 - (NSString*)scriptToExecutePOSTRequest:(NSURLRequest*)request;
43
44 // Converts a dictionary of HTTP request headers to a JavaScript object.
45 - (NSString*)JSONForJavaScriptFromRequestHeaders:(NSDictionary*)headers;
46
47 @end
48
49 @implementation CRWJSPOSTRequestLoader
50
51 - (instancetype)init {
52 self = [super init];
53 if (self) {
54 [[NSNotificationCenter defaultCenter]
55 addObserver:self
56 selector:@selector(handleMemoryWarning)
57 name:UIApplicationDidReceiveMemoryWarningNotification
58 object:nil];
59 }
60 return self;
61 }
62
63 - (void)dealloc {
64 [[NSNotificationCenter defaultCenter] removeObserver:self];
65 [super dealloc];
66 }
67
68 - (NSString*)requestScript {
69 if (!_requestScript) {
70 _requestScript.reset([web::GetPageScript(@"post_request") copy]);
71 }
72 return _requestScript;
73 }
74
75 - (void)loadPOSTRequest:(NSURLRequest*)request
76 inWebView:(WKWebView*)webView
77 messageRouter:(CRWWKScriptMessageRouter*)messageRouter
78 completionHandler:(void (^)(NSError*))completionHandler {
79 DCHECK([request.HTTPMethod isEqualToString:@"POST"]);
80 DCHECK(webView);
81 DCHECK(messageRouter);
82 DCHECK(completionHandler);
83
84 // Install error handling and success routers.
85 [messageRouter setScriptMessageHandler:^(WKScriptMessage* message) {
86 // Cleaning up script handlers.
87 [messageRouter removeScriptMessageHandlerForName:kErrorHandlerName
88 webView:webView];
89 [messageRouter removeScriptMessageHandlerForName:kSuccessHandlerName
90 webView:webView];
91 completionHandler(nil);
92 }
93 name:kSuccessHandlerName
94 webView:webView];
95
96 [messageRouter setScriptMessageHandler:^(WKScriptMessage* message) {
97 NSNumber* statusCode = message.body;
98 NSError* error = [NSError errorWithDomain:NSURLErrorDomain
99 code:statusCode.integerValue
100 userInfo:nil];
101 [messageRouter removeScriptMessageHandlerForName:kErrorHandlerName
102 webView:webView];
103 [messageRouter removeScriptMessageHandlerForName:kSuccessHandlerName
104 webView:webView];
105 completionHandler(error);
106 }
107 name:kErrorHandlerName
108 webView:webView];
109
110 NSString* HTML =
111 [NSString stringWithFormat:@"<html><script>%@%@</script></html>",
112 self.requestScript,
113 [self scriptToExecutePOSTRequest:request]];
114 [webView loadHTMLString:HTML baseURL:request.URL];
115 }
116
117 #pragma mark - Private methods.
118
119 - (void)handleMemoryWarning {
120 // Request script can be recreated from file at any moment.
121 _requestScript.reset();
122 }
123
124 - (NSString*)scriptToExecutePOSTRequest:(NSURLRequest*)request {
125 NSDictionary* headers = [request allHTTPHeaderFields];
126 NSString* headerString = [self JSONForJavaScriptFromRequestHeaders:headers];
127 NSString* URLString = [[request URL] absoluteString];
128 NSString* contentType = headers[@"Content-Type"];
129 NSString* base64Data = [[request HTTPBody] base64EncodedStringWithOptions:0];
130
131 // Here |headerString| is already properly escaped when returned from
132 // -JSONForJavaScriptFromRequestHeaders:.
133 return
134 [NSString stringWithFormat:
135 @"__crPostRequestWorkaround.runPostRequest(%@, %@, %@, %@)",
136 EscapeAndQuoteStringForJavaScript(URLString), headerString,
137 EscapeAndQuoteStringForJavaScript(base64Data),
138 EscapeAndQuoteStringForJavaScript(contentType)];
139 }
140
141 - (NSString*)JSONForJavaScriptFromRequestHeaders:(NSDictionary*)headers {
142 if (headers) {
143 NSData* headerData =
144 [NSJSONSerialization dataWithJSONObject:headers options:0 error:nil];
145 if (headerData) {
146 // This string is properly escaped by NSJSONSerialization. It needs to
147 // have no quotes since JavaScripts takes this parameter as an
148 // Object<string, string>.
149 return [[[NSString alloc] initWithData:headerData
150 encoding:NSUTF8StringEncoding] autorelease];
151 }
152 }
153 return @"{}";
154 }
155
156 @end
OLDNEW
« no previous file with comments | « ios/web/web_state/js/crw_js_post_request_loader.h ('k') | ios/web/web_state/js/crw_js_post_request_loader_unittest.mm » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698