美文网首页ios
WKWebView支持自动缩放网页(亲测可用)

WKWebView支持自动缩放网页(亲测可用)

作者: 上帝是个女孩丶 | 来源:发表于2018-08-30 11:05 被阅读433次

WKWebView自动缩放网页

UIWebView有scalespagetofit属性,自动帮我们缩放网页了。但是UIWebView存在漏洞,且性能太差被遗弃。替换WK后发现网页内容不能自动缩放了。网上搜了很多答案,发现都不能用。最终Google一个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);";
    
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;
    
    WKWebView *webview = [[WKWebView alloc]initWithFrame:self.rendererBaseView.bounds configuration:wkWebConfig];
    webview.backgroundColor = [UIColor clearColor];
    webview.opaque = NO;
    webview.userInteractionEnabled = NO;
    webview.scrollView.scrollEnabled = NO;

重点:
很多人反馈加了这个JS一样不生效,注意网页的加载方式!要用HTML的load方式:

NSString *htmlStr = [NSString stringWithFormat:@"%@", @"<html><body><img src='%@' width='%f' height='%f' style='margin: -8px -8px'/></body></html>"];
NSString *imageHTML  = [[NSString alloc] initWithFormat:htmlStr, path,adImageSize.width, adImageSize.height];

[webview loadHTMLString:imageHTML baseURL:[NSURL URLWithString:@"file:///"]];

这种直接loadrequest的是不行的:
[webView loadRequest:request];

UIWebView漏洞链接:https://mp.weixin.qq.com/s/ZBMCgoQnYIUHVjrUHOlv4g

WKWebView播放gif

WKWebView文件域是安全了,但是这样也顺带导致了我们不能直接从沙盒中读取内容了。因此模拟器可以正常播放gif,真机却不行。

解决方案:
替换本地文件存储路径,目前测试发现tmp文件目录是可用的,只有该目录下的文件可读取,但是存在的问题是该文件会不定时被系统清理。。(允悲)
获取沙盒各种目录路径:
1,获取家目录路径的函数:
NSString *homeDir = NSHomeDirectory();
2,获取Documents目录路径的方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
3,获取Caches目录路径的方法:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
4,获取tmp目录路径的方法:
NSString *tmpDir = NSTemporaryDirectory();
5,获取应用程序程序包中资源文件路径的方法:

NSString *path = [[NSBundle mainBundle] pathForResource:@”name” ofType:@”gif”];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:path];

注意:IOS做move操作的时候,第一源文件需要存在,第二目标文件不能存在,且需要指定move后的文件名。最好是拿源文件的名字来作为move后的文件名字。

相关文章

网友评论

    本文标题:WKWebView支持自动缩放网页(亲测可用)

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