WKWebView JavaScript 将消息发送到 Objective-C 和 returns 值
The WKWebView JavaScript sends the message to Objective-C and returns the value
如何使用WKWebView,JavaScript将消息发送到Objective-C和returns值。
像这样:
让结果 = window.webkit.messageHandlers.name.postMessage();
Adding a script message handler with name name
causes the JavaScript function window.webkit.messageHandlers.name.postMessage(messageBody) to be defined in all frames in all web views that use the user content controller.
https://developer.apple.com/reference/webkit/wkusercontentcontroller/1537172-add
我找到了另一种方法,通过WKUserScriptInjectionTimeAtDocumentStart参数注入js到web的localStorage。
像这样:
NSString *token = [NSString stringWithFormat:@"localStorage.setItem(\"accessToken\",'%@');",@"74851c23358c"];
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:sendToken injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"iOS"];
[config.userContentController addUserScript:wkUScript];
WKWebView *webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) configuration:config];
如何使用WKWebView,JavaScript将消息发送到Objective-C和returns值。
像这样:
让结果 = window.webkit.messageHandlers.name.postMessage();
Adding a script message handler with name name causes the JavaScript function window.webkit.messageHandlers.name.postMessage(messageBody) to be defined in all frames in all web views that use the user content controller.
https://developer.apple.com/reference/webkit/wkusercontentcontroller/1537172-add
我找到了另一种方法,通过WKUserScriptInjectionTimeAtDocumentStart参数注入js到web的localStorage。 像这样:
NSString *token = [NSString stringWithFormat:@"localStorage.setItem(\"accessToken\",'%@');",@"74851c23358c"];
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:sendToken injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"iOS"];
[config.userContentController addUserScript:wkUScript];
WKWebView *webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) configuration:config];