Basic realization ideas:
- Put an HTML code containing a POST request for JavaScript in the project directory
- Load the code for this POST request containing JavaScript to WK WebView
- After loading is completed, the POST method of JavaScript is called with Native and parameters are passed in to complete the request.
- Create HTML code for POST requests containing JavaScript
Related codes:
<html> <head> <script> //Call format: post('URL', {"key": "value"}; function post(path, params) { var method = "post"; var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } } document.body.appendChild(form); form.submit(); } </script> </head> <body> </body> </html>
Copy this code and paste it into the text editor. The name can be saved as JSPOST.html. Then copy it to the project directory. Remember to select the corresponding Target and check Copy items if needed (the default should be checked). At this point, you can use this JavaScript code to send POST requests with parameters.
Load the corresponding JavaScript code into WK WebView by loading the local web page
=========== OC code: ============
// JS sends Flag of POST and calls the POST method of JS when it is true (loading local JS only the first time) self.needLoadJSPOST = YES;
//Create WK WebView
self.webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
// Setting up Agents
self.webView.navigationDelegate = self;
// Get the path where the JS is located
NSString *path = [[NSBundle mainBundle] pathForResource:@"JSPOST" ofType:@"html"];
// Get html content
NSString *html = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
/ / loading js
[self.webView loadHTMLString:html baseURL:[[NSBundle mainBundle] bundleURL]];
// Add WK WebView to the current View
[self.view addSubview:self.webView];
========= Swift code: ============
// JS sends Flag of POST and calls the POST method of JS when it is true (loading local JS only the first time)
needLoadJSPOST = true
//Create WK WebView
webView = WKWebView(frame: UIScreen.mainScreen().bounds)
// Setting up Agents
webView.navigationDelegate = self
// Get the JS path
let path = NSBundle.mainBundle().pathForResource("JSPOST", ofType: "html")
// Get html content
do { let html = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) // Loading js webView.loadHTMLString(html, baseURL: NSBundle.mainBundle().bundleURL) } catch { }
// Add WK WebView to the current View
view.addSubview(webView)
This code is equivalent to loading the JavaScript script in the project into the WKWebView, and then see how to use it. (Note to change your file name)
Native calls JavaScript scripts and passes in parameters to complete POST requests
Remember the section on interaction between WK WebView and JavaScript? Now it's time for Native to call JavaScript. If you forget, please go ahead and review it. - webView: didFinish Navigation: The proxy indicates that the page has been loaded. We'll do it here. Here's the code:
=========== OC code: ============
// Proxy method for load completion
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { // Determine whether loading is required (only for the first time) if (self.needLoadJSPOST) { // Call the method of sending POST requests using JS [self postRequestWithJS]; // Set Flag to NO (you don't need to load it later) self.needLoadJSPOST = NO; } } // Call JS to send POST requests - (void)postRequestWithJS { // Send POST parameters NSString *postData = @"\"username\":\"aaa\",\"password\":\"123\""; // The requested page address NSString *urlStr = @"http://www.postexample.com"; // String assembled to call JavaScript NSString *jscript = [NSString stringWithFormat:@"post('%@', {%@});", urlStr, postData]; // NSLog(@"Javascript: %@", jscript); // Call JS code [self.webView evaluateJavaScript:jscript completionHandler:^(id object, NSError * _Nullable error) { }]; }
==========Swift code: =============
// Proxy method for load completion
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) { // Determine whether loading is required (only for the first time) if needLoadJSPOST { // Call the method of sending POST requests using JS postRequestWithJS() // Set Flag to NO (you don't need to load it later) needLoadJSPOST = false } } // Call JS to send POST requests func postRequestWithJS() { // Send POST parameters let postData = "\"username\":\"aaa\",\"password\":\"123\"" // The requested page address let urlStr = "http://www.postexample.com" // String assembled to call JavaScript let jscript = "post('\(urlStr)', {\(postData)});" // Call JS code webView.evaluateJavaScript(jscript) { (object, error) in } }
End.