WKWebView加載HTML標簽注意事項

首先解決自適應屏幕寬度的問題
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *content = [[WKUserContentController alloc]init];
    // 自適應屏幕寬度js
    NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *wkUserScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    // 添加自適應屏幕寬度js調用的方法
    [content addUserScript:wkUserScript];
    wkWebConfig.userContentController = content;
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth , 0) configuration:wkWebConfig];
    webView.scrollView.bounces = NO;
    webView.UIDelegate = self;
    webView.navigationDelegate = self;
    webView.scrollView.scrollEnabled = NO;
    self.webView = webView;
    [self.mainScrollView addSubview:webView];
其次計算高度
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    //修改字體大小 300%
//    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'" completionHandler:nil];
    
    //修改字體顏色  #9098b8
//    [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#0078f0'" completionHandler:nil];
    
    __block CGFloat webViewHeight;
    
    //獲取內容實際高度(像素)@"document.getElementById(\"content\").offsetHeight;"
    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
        // 此處js字符串采用scrollHeight而不是offsetHeight是因為后者并獲取不到高度,看參考資料說是對于加載html字符串的情況下使用后者可以(@"document.getElementById(\"content\").offsetHeight;"),但如果是和我一樣直接加載原站內容使用前者更合適
        //獲取頁面高度,并重置webview的frame
        webViewHeight = [result floatValue];
        webView.height = webViewHeight;
        self.mainScrollView.contentSize = CGSizeMake(KScreenWidth, webView.top + webViewHeight);
        NSLog(@"%f",webViewHeight);
        
        
    }];

}

如果加載HTML圖片的時候失敗,可能是info.plist文件沒加網絡權限
Allow Arbitrary Loads in Web Content   
Allow Arbitrary Loads
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。