简体   繁体   中英

The WKWebView JavaScript sends the message to Objective-C and returns the value

How to use WKWebView,JavaScript sends the message to Objective-C and returns the value.

like this:

let result = 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

I found another way,Through the WKUserScriptInjectionTimeAtDocumentStart parameters into js to the web's localStorage. like this:

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM