美文网首页
WKWebView JS注入

WKWebView JS注入

作者: zxh123456 | 来源:发表于2021-11-03 13:40 被阅读0次

    碰到个webview页面突然被放大了,查看html源码发现:

    <meta name="viewport" content="initial-scale=0.3333333333333333, maximum-scale=0.3333333333333333, minimum-scale=0.3333333333333333, user-scalable=no">
    

    所以想到了对html进行js注入

    WKUserScriptInjectionTimeAtDocumentStart : 注入时机为document的元素生成以后,其余内容load以前.

    WKUserScriptInjectionTimeAtDocumentEnd : 注入时机为document所有load完成,任意子资源load完成以前.

    - (WKWebView *)webView
    {
        if (!_webView) {
            NSString *jScript = @"var script = document.createElement('meta');script.name = 'viewport';script.content='width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no';document.getElementsByTagName('head')[0].appendChild(script);";
            //注意修改meta的js注入一定要选WKUserScriptInjectionTimeAtDocumentStart,否则不生效
            WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
            WKUserContentController * wkUController = [[WKUserContentController alloc] init];
            [wkUController addUserScript:wkUScript];
            WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
            wkWebConfig.userContentController= wkUController;
    
            _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0 , 375, 812)  configuration:wkWebConfig];
            _webView.backgroundColor = [UIColor whiteColor];
            _webView.navigationDelegate = self;
            _webView.UIDelegate = self;
        }
        
        return _webView;
    }
    

    相关文章

      网友评论

          本文标题:WKWebView JS注入

          本文链接:https://www.haomeiwen.com/subject/svzqzltx.html