WKWebview 中 JS 和 OC 的交互

WKWebView 中 JS 和 OC 的交互主要用到 WKUserContentController WKUserScript 這個(gè)類,關(guān)于 WKUserContentController api的講解請看
WKWebView API詳解 這篇文章

注入JS 代碼

// JS代碼
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
// 生成 UScript
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
// 生成 UController
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
// 添加 JS
[wkUController addUserScript:wkUScript];
// 配置
WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
wkWebConfig.userContentController = wkUController;
_webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wkWebConfig];

執(zhí)行 JS 代碼,獲得 webView 的高度

// 加載 js 下面的 js 代碼獲取高度,但是這種方法獲取的高度可能不準(zhǔn)確,因?yàn)橛袌D片或者視頻沒有加載出來的情況,內(nèi)容會有被遮住一部分的情況。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
      // 1.document.documentElement.offsetHeight
      // 2.document.body.clientHeight
      // 3.document.documentElement.scrollHeight
    webView.evaluateJavaScript("document.body.clientHeight") { (result, error) in
        if error != nil { return }
        let height = result as! CGFloat
    }
}

JS 調(diào)用 OC 代碼(JS 向 OC 發(fā)消息)

// 生成 UController
WKUserContentController *wkUController = [[WKUserContentController alloc] init];
// 添加一個(gè) webShare方法供給 JS 調(diào)用
[wkUController addScriptMessageHandler:self name:@"webShare"];

JS 調(diào)用添加的 webShare 方法

function postMessage(){
    var message = {'title':'title','url':'www.baidu.com'}
    window.webkit.messageHandlers.webShare.postMessage({body: message});
}

JS 發(fā)送過來的數(shù)據(jù)

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"js oc name:%@ body:%@",message.name,message.body);
}

完整的代碼:

#import "ViewController.h"
@import WebKit;

@interface ViewController ()<WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.view addSubview:self.webView];
}

- (WKWebView *)webView
{
    if (_webView == nil) {
        // JS代碼
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        // 生成 UScript
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        // 生成 UController
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        // 添加 JS
        [wkUController addUserScript:wkUScript];
        [wkUController addScriptMessageHandler:self name:@"webShare"];

        // 配置
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.userContentController = wkUController;
        
        _webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:wkWebConfig];

        NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"local" ofType:@"html"];
        NSString * appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
        [_webView loadHTMLString:appHtml baseURL:nil];
    }
    return _webView;
}

- (void)dealloc{
    [[_webView configuration].userContentController removeAllUserScripts];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"webShare"];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"js oc name:%@ body:%@",message.name,message.body);
}

html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div>
        <button onclick="postMessage();">發(fā)消息</button>
    </div>
<script>

function postMessage(){
    alert('123')
    var message = {'title':'title','url':'www.baidu.com'}
    window.webkit.messageHandlers.webShare.postMessage({body: message});
}
</script>
</body>
</html>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容