make WKWebview “real” fullscreen on iPhone X (remove safe area from WKWebView

半世苍凉 提交于 2019-11-30 11:56:22

After a little try and error, this is the solution I came up with. Subclass WKWebView and create a custom class. Overwrite safeAreaInsets:

import Foundation
import WebKit

class FullScreenWKWebView: WKWebView {
    override var safeAreaInsets: UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
}

Use AutoLayout constraints instead:

NSLayoutConstraint.activate([
    webView.topAnchor.constraint(equalTo: view.topAnchor),
    webView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
    webView.leftAnchor.constraint(equalTo: view.leftAnchor),
    webView.rightAnchor.constraint(equalTo: view.rightAnchor)
])

Remember to add viewport-fit=cover to your webpage's viewport meta tag, and use Safari's new variables to add padding to your content, to make sure that it respects the safe areas.

/* iOS 11 */
constant(safe-area-inset-*);
/* iOS 11.2 */
env(safe-area-inset-*);

Edit

I was also exploring options for adding the meta tag without doing any changes on the actual webpage. If I remember correctly I did succeed in adding the meta tag through Swift with the following piece of code:

webView.evaluateJavascript("document.querySelector('meta[name=viewport]').content = document.querySelector('meta[name=viewport]').content + ', viewport-fit=cover'", completionHandler: nil)

This is for use in a WKWebView by the way, and you'll need to execute it after the webpage has loaded obviously. Also some error handling should probably be done, as this will throw an exception if a metatag named viewport is missing, and the content will be , viewport-fit=cover if the content is empty to begin with.

You can also extend safeAreaInsets from WKWebView.

extension WKWebView {
    override open var safeAreaInsets: UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!